Imports System.Data.SqlClient
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraGrid.Views.Grid

'--- Created By : Jagdish
'--- Created On : 05-Oct-2010

Public Class frmDoctorsNote
    Dim mblnActivate As Boolean = True
    Dim mblnChanged As Boolean = False
    Dim lblHistory As DevExpress.XtraEditors.LabelControl() 'Label()    'create label array for pastHitory tab
    Dim txtHistory As DevExpress.XtraEditors.TextEdit()    'TextBox()  'create textbox array for past history tab

    Dim dtSeverity As New DataTable

    Public VisitId As Integer = Nothing 'This is VisitId of patient ,for which doctor will write his notes
    Private PatientId As Integer
    Public mstrFrmName As String = ""    'This is Used for not prompting the user the message Is Visit Complete when opened from Patient Info form
    Private IsCloseForm As Boolean = False
    Private AllergyTextBoxTag As Integer 'this variable is used to store the  tag of a textbox in which we store the allergy control
    Dim lstMedicine As New DevExpress.XtraEditors.CheckedListBoxControl
    Dim IsThisTabPopulated() As Boolean
    Dim SpecialistsIndices(), LabTestIndices(), ImagingIndices(), AllergyHistoryIndices() As Integer
    Dim UrineTestForm As frmUrineTest
    Dim WithEvents rpglkActiveDiagnosis As RepositoryItemGridLookUpEdit
    Dim WithEvents rpglkActiveSeverity As RepositoryItemGridLookUpEdit
    Dim WithEvents rpdtActiveDiagnosisDate As RepositoryItemDateEdit
    Dim WithEvents rpglkInActiveDiagnosis As RepositoryItemGridLookUpEdit
    Dim WithEvents rpglkInActiveSeverity As RepositoryItemGridLookUpEdit
    Dim WithEvents rpdtInActiveDiagnosisDate As RepositoryItemDateEdit
    Dim WithEvents rpdtInActiveResolveDate As RepositoryItemDateEdit
    Dim WithEvents rpglkDrugName As RepositoryItemGridLookUpEdit
    Dim WithEvents rpglkDrugUnit As RepositoryItemGridLookUpEdit
    Dim WithEvents rptxtDrugDose As RepositoryItemTextEdit
    Dim WithEvents rptxtDrugfrequency As RepositoryItemGridLookUpEdit
    Dim WithEvents rptxtDrugComment As RepositoryItemMemoEdit
    Public PresentHistory As String
    Public GeneralAssessment As String
    Dim blnUnload As Boolean
    Dim blnIsSaved As Boolean = False



    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

        'assign this id to urinetest form, which is a control on this form (in Genito Urinary Tab)
        'we dont want this form to exit on save,hence set second argument to false
        UrineTestForm = New frmUrineTest(VisitId, False)

    End Sub

    Private Shared m_vb6FormDefInstance As frmDoctorsNote
    Private Shared m_InitializingDefInstance As Boolean
    Public Shared Property DefInstance() As frmDoctorsNote
        Get
            If m_vb6FormDefInstance Is Nothing OrElse m_vb6FormDefInstance.IsDisposed Then
                m_InitializingDefInstance = True
                m_vb6FormDefInstance = New frmDoctorsNote
                m_InitializingDefInstance = False
            End If
            DefInstance = m_vb6FormDefInstance
        End Get
        Set(ByVal Value As frmDoctorsNote)
            m_vb6FormDefInstance = Value
        End Set
    End Property

#Region "PresentHistory Page"

    Private Sub SavePresentHistory()
        'Patient is already registered ,so there is no need to check wheather visitId exist or not
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            strQuery = "PresentingComplaint=" & Trim(SmartReplace(txtPC.Text) & "")
            strQuery = strQuery & ",PresentingComplaintHistory=" & Trim(SmartReplace(txtComplaintHistory.Text) & "")
            strQuery = strQuery & ",History=" & Trim(SmartReplace(txtSummaryHistory.Text) & "")
            Call UpdateTable("tblVisits", strQuery, "VisitId=" & VisitId)
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try


    End Sub

#End Region

#Region "PastHistory Page"


    Private Sub PopulatePastHistoryControls()
        Dim VerticalOffset As Integer = 90       'Specifies distance between two labels or textboxes ,vertically
        Dim HorizontalOffset As Integer = 246    'Specifies distance between two labels or textboxes ,Horizontally
        Dim HistoryTypeCount As Integer          'total no of Label+TextBoxes  to be displayed
        Dim RowCount As Integer = 5              'No of  Label+TextBoxes vertically
        Dim ColumnCount As Integer               'No of  Label+TextBoxes Horizontally ,it is calculated later

        Dim StartPoint As New Point(16, 10)       'Point where first Label+TextBox will be shown
        Dim LabelSize As New Size(200, 16)       'Size of each label  
        Dim TextBoxSize As New Size(205, 70)     'Size of each textBox

        Dim strQuery As String
        Dim dsTemp As DataSet
        Try
            strQuery = "SELECT COUNT(HistoryTypeId) as CNT FROM LtblHistoryType"    'Query to find no. of History types
            dsTemp = FillDataSet(strQuery)
            If dsTemp.Tables(0).Rows(0).Item("CNT") > 0 Then
                HistoryTypeCount = dsTemp.Tables(0).Rows(0).Item("CNT") 'Get no. of History Types ,Used in loop as a count
            End If
            dsTemp.Dispose()

            ColumnCount = HistoryTypeCount / RowCount  'Calculate Column Count

            ReDim Preserve lblHistory(HistoryTypeCount - 1) 'redim label array to the size equal to history types
            ReDim Preserve txtHistory(HistoryTypeCount - 1) 'redim text array to the size equal to history types

            strQuery = "SELECT * FROM LtblHistoryType"
            dsTemp = FillDataSet(strQuery)

            Dim i, j, k As Integer                   'variables for  loop
            Dim l As Integer             'index of array

            For i = 0 To HistoryTypeCount - 1           'Outer loop,that determines how many controls to draw
                For k = 0 To ColumnCount - 1            'middle loop, no. of Label+TextBoxes  column
                    For j = 0 To RowCount - 1           'inner loop , no. Label+TextBoxes per column 
                        If l = HistoryTypeCount Then Exit For
                        If dsTemp.Tables(0).Rows.Count <= 0 Then 'Read record
                            txtHistory(0).Focus() 'focus very first text box
                            Exit Sub              'No data,exit sub
                        End If

                        lblHistory(l) = New DevExpress.XtraEditors.LabelControl
                        lblHistory(l).Location = New Point(StartPoint.X + HorizontalOffset * k, StartPoint.Y + VerticalOffset * j)
                        lblHistory(l).Size = LabelSize
                        lblHistory(l).Text = dsTemp.Tables(0).Rows(l).Item("HistoryType")
                        lblHistory(l).Font = New Font("Microsoft Sans Serif", 9, FontStyle.Regular)


                        txtHistory(l) = New DevExpress.XtraEditors.MemoEdit
                        txtHistory(l).Location = New Point(StartPoint.X + HorizontalOffset * k, StartPoint.Y + LabelSize.Height + VerticalOffset * j)
                        txtHistory(l).Size = TextBoxSize
                        txtHistory(l).Font = New Font("Microsoft Sans Serif", 9, FontStyle.Regular)
                        txtHistory(l).BringToFront()
                        'txtHistory(l).Multiline = True
                        'txtHistory(l).ScrollBars = ScrollBars.Vertical
                        txtHistory(l).Tag = dsTemp.Tables(0).Rows(l).Item("HistoryTypeId")   'Add information about historytypeid in tag,it will be used later while saving

                        'if History type is allergy then make it multiselect check box control
                        If dsTemp.Tables(0).Rows(l).Item("HistoryType") = "Drug Allergy" Then
                            lstMedicine.Location = New Point(StartPoint.X + HorizontalOffset * k, StartPoint.Y + LabelSize.Height + VerticalOffset * j)
                            lstMedicine.Size = TextBoxSize
                            lstMedicine.Font = New Font("Microsoft Sans Serif", 9, FontStyle.Regular)
                            lstMedicine.CheckOnClick = True
                            lstMedicine.Show()
                            lstMedicine.IncrementalSearch = True
                            lstMedicine.BringToFront()
                            lstMedicine.ToolTip = "Double click to add new drug allergy"

                            'PopulateList(lstMedicine, "SELECT  LtblDrugs.DrugId, LtblDrugs.DrugName FROM LtblDrugs JOIN tblDrugs ON LtblDrugs.DrugId=tblDrugs.DrugId WHERE tblDrugs.DrugDeleted=0 ORDER BY LtblDrugs.DrugName", "DrugName", "DrugId")
                            Call PopulateCheckedListboxDX(lstMedicine, "DrugName", "DrugId", "LtblDrugs ", "LtblDrugs.DrugId [DrugId], LtblDrugs.DrugName [DrugName]", , "[DrugName]")
                            AllergyTextBoxTag = txtHistory(l).Tag

                            'txtHistory(l).Controls.Add(lstMedicine)
                            Me.tpgPastHistory.Controls.Add(lstMedicine)
                            AddHandler lstMedicine.DoubleClick, AddressOf AddNewAllergy
                            txtHistory(l).Visible = False
                        End If

                        'add these controls to the Past history tabpage
                        Me.tpgPastHistory.Controls.Add(lblHistory(l))
                        Me.tpgPastHistory.Controls.Add(txtHistory(l))

                        l = l + 1 'increment index of array
                    Next
                Next
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Sub AddNewAllergy()
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblDrugs"
            .mintGrbId = 1
            .ShowInTaskbar = False
            .ShowDialog()
            Call PopulateCheckedListboxDX(lstMedicine, "DrugName", "DrugId", "LtblDrugs", "LtblDrugs.DrugId [DrugId], LtblDrugs.DrugName [DrugName]", , "[DrugName]")
            .Dispose()
            GC.Collect()
        End With
    End Sub
    Private Sub SavePastHistory()
        'If MessageBox.Show("This will update all the previously saved records.Do you want to save?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then
        '    Exit Sub
        'End If

        Dim PatientId As Integer
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            'get patientId for that visitId
            Dim dsTemp As DataSet = FillDataSet("Select PatientId FROM tblVisits WHERE VisitId=" & VisitId)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                PatientId = dsTemp.Tables(0).Rows(0).Item("PatientId")
            End If
            'Delete all the rows for that patiet
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            Call DeleteFromTable("tblVisitPastHistory", "PatientId=" & PatientId)

            'create datatable and its column for tblVisitPastHistory
            '' '' ''Dim dt As New DataTable

            '' '' ''Dim PatientIdCol, HistoryTypeIdCol, HistoryCol As DataColumn

            '' '' ''PatientIdCol = New DataColumn("PatientIdCol", GetType(Int32))
            '' '' ''HistoryTypeIdCol = New DataColumn("HistoryTypeIdCol", GetType(Int32))
            '' '' ''HistoryCol = New DataColumn("HistoryCol", GetType(String))

            '' '' ''dt.Columns.Add(PatientIdCol)
            '' '' ''dt.Columns.Add(HistoryTypeIdCol)
            '' '' ''dt.Columns.Add(HistoryCol)


            Dim i As Integer 'loop variable
            '' '' ''Dim row As DataRow

            'read the description in textboxes and store them in datarow of datatable
            For i = 0 To txtHistory.GetLength(0) - 1
                If txtHistory(i).Tag = AllergyTextBoxTag Then
                    'this text box contain no info,insted we use checked list box 
                    Dim count As Integer
                    Dim MedicationIdString As String = String.Empty
                    For count = 0 To lstMedicine.ItemCount - 1
                        If lstMedicine.GetItemChecked(count) = True Then
                            'MedicationIdString = MedicationIdString & lstMedicine.Items(count).Item("DrugId") & ","
                            MedicationIdString = MedicationIdString & lstMedicine.GetItemValue(count) & ","
                        End If
                    Next

                    'remove the trailing ","  i.e. commas
                    If MedicationIdString <> String.Empty Then
                        MedicationIdString = MedicationIdString.Substring(0, MedicationIdString.LastIndexOf(","))
                    End If

                    txtHistory(i).Text = MedicationIdString.Trim
                    MedicationIdString = String.Empty 'assingn empty string so that when we press save button again new info will not append to  MedicationIdString
                End If

                '' '' ''row = dt.NewRow
                '' '' ''row.Item("PatientIdCol") = Convert.ToInt32(PatientId)
                '' '' ''row.Item("HistoryTypeIdCol") = Convert.ToInt32(txtHistory(i).Tag)
                '' '' ''row.Item("HistoryCol") = txtHistory(i).Text.Trim
                '' '' ''dt.Rows.Add(row)
                strQuery = PatientId
                strQuery = strQuery & "," & txtHistory(i).Tag
                strQuery = strQuery & "," & Trim(SmartReplace(txtHistory(i).Text) & "") & ""
                Call InsertintoTable("tblVisitPastHistory", strQuery)
            Next

            'now store these rows in datatable

            '' '' ''cn.Open()

            '' '' ''Dim dcInsert As New SqlCommand
            '' '' ''dcInsert.CommandText = "INSERT INTO tblVisitPastHistory(" & IIf(ServerType = "sub", "VisitPastHistoryId, ", String.Empty) & " PatientId,HistoryTypeId,History) VALUES (" & IIf(ServerType = "sub", "@VisitPastHistoryId, ", String.Empty) & " @PatientId,@HistoryTypeId,@History)"
            '' '' ''dcInsert.Connection = cn

            '' '' ''If (ServerType = "sub") Then
            '' '' ''    dcInsert.Parameters.Add(New SqlParameter("@VisitPastHistoryId", SqlDbType.Int, 4, "VisitPastHistoryId"))
            '' '' ''End If
            '' '' ''dcInsert.Parameters.Add(New SqlParameter("@PatientId", SqlDbType.Int, 4, "PatientId"))
            '' '' ''dcInsert.Parameters.Add(New SqlParameter("@HistoryTypeId", SqlDbType.Int, 4, "HistoryTypeId"))
            '' '' ''dcInsert.Parameters.Add(New SqlParameter("@History", SqlDbType.VarChar, 255, "History"))


            '' '' ''Dim r As DataRow
            '' '' ''For Each r In dt.Rows
            '' '' ''    With dcInsert
            '' '' ''        If (ServerType = "sub") Then
            '' '' ''            .Parameters("@VisitPastHistoryId").Value = GetNextId("tblVisitPastHistory", "VisitPastHistoryId")
            '' '' ''        End If
            '' '' ''        .Parameters("@PatientId").Value = r.Item("PatientIdCol")
            '' '' ''        .Parameters("@HistoryTypeId").Value = r.Item("HistoryTypeIdCol")
            '' '' ''        .Parameters("@History").Value = r.Item("HistoryCol")
            '' '' ''        .ExecuteNonQuery()
            '' '' ''    End With
            '' '' ''Next

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try



    End Sub
#End Region

#Region "GeneralAssessment Page"

    Private Sub PopulateGenAssessmentCombos()
        'Populate height   combo 
        Call PopulateLookupDX(cmbHeightUnit, "LengthUnits", "LengthId", "LtblUnitsLength", "LengthId,LengthUnits", , "LengthUnits", , , 50)

        'Populate  girth combos
        Call PopulateLookupDX(cmbAbdominalGirthUnit, "LengthUnits", "LengthId", "LtblUnitsLength", "LengthId,LengthUnits", , "LengthUnits", , , 50)

        'Populate  head circumference  combos
        Call PopulateLookupDX(cmbHeadCircumferenceUnit, "LengthUnits", "LengthId", "LtblUnitsLength", "LengthId,LengthUnits", , "LengthUnits", , , 50)

        'Populate weight combos
        Call PopulateLookupDX(cmbWeightUnit, "WeightUnit", "WeightId", "LtblUnitsWeight", "WeightId,WeightUnit", , "WeightUnit", , , 50)

        'Populate temprature combos
        Call PopulateLookupDX(cmbTemperatureUnit, "TempUnit", "TempUnitId", "LtblUnitsTemp", "TempUnitId,TempUnit", , "TempUnit", , , 50)
    End Sub

    Private Function IsGeneralAssessmentValid() As Boolean
        If Trim(txtJVPHeight.Text) <> "" Then
            If Trim(txtJVPHeight.Text) = 0 OrElse Trim(txtJVPHeight.Text) < 0 Then
                MessageBox.Show("Please enter proper Height.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                xtcNotes.SelectedTabPage = tpgGeneralAssessment
                txtJVPHeight.Focus()
                txtJVPHeight.SelectAll()
                Return False
            End If
        End If

        If Trim(txtWeight.Text) <> "" Then
            If Trim(txtWeight.Text) < 0 OrElse Trim(txtWeight.Text) = 0 Then
                MessageBox.Show("Please enter proper Weight.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                xtcNotes.SelectedTabPage = tpgGeneralAssessment
                txtWeight.Focus()
                txtWeight.SelectAll()
                Return False
            End If
        End If



        If Trim(txtTemperature.Text) <> "" Then
            If Trim(txtTemperature.Text) < 0 AndAlso Trim(txtTemperature.Text) = 0 Then
                MessageBox.Show("Please enter proper Temperature.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                xtcNotes.SelectedTabPage = tpgGeneralAssessment
                txtTemperature.Focus()
                txtTemperature.SelectAll()
                Return False
            End If
        End If

        If Trim(txtAbdominalGirth.Text) <> "" Then
            If Trim(txtAbdominalGirth.Text) < 0 AndAlso Trim(txtAbdominalGirth.Text) = 0 Then
                MessageBox.Show("Please enter proper Abdominal Girth.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                xtcNotes.SelectedTabPage = tpgGeneralAssessment
                txtAbdominalGirth.Focus()
                txtAbdominalGirth.SelectAll()
                Return False
            End If
        End If


        If Trim(txtHeadCircimference.Text) <> "" Then
            If Trim(txtHeadCircimference.Text) < 0 AndAlso Trim(txtHeadCircimference.Text) = 0 Then
                MessageBox.Show("Please enter proper Head Circimference.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                xtcNotes.SelectedTabPage = tpgGeneralAssessment
                txtHeadCircimference.Focus()
                txtHeadCircimference.SelectAll()
                Return False
            End If
        End If

        Return True
    End Function

    Private Sub SaveGenAssessment()


        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Dim Cnt As Integer
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Cnt = Val(strRecordID("tblVisitGeneralAssessment", "VisitAssessmentId", "VisitId=" & VisitId))
            If Cnt > 0 Then
                'strQuery = "GeneralCondition=" & Trim(SmartReplace(txtGeneralCondition.Text) & "") & "" & _
                '             ", Nutrition=" & Trim(SmartReplace(cmbNutrition.Text) & "") & "" & _
                '             ", MucusMebrane1=" & Trim(SmartReplace(cmbMucus1.Text) & "") & "" & _
                '             ", MucusMebrane2=" & Trim(SmartReplace(cmbMucus2.Text) & "") & "" & _
                '             ", MucusMebrane3=" & Trim(SmartReplace(cmbMucus3.Text) & "") & "" & _
                '             ", MucusMebrane4=" & Trim(SmartReplace(cmbMucus4.Text) & "") & "" & _
                '             ", Hydration=" & Trim(SmartReplace(cmbHydration.Text) & "") & "" & _
                '             ", Oedema=" & Trim(SmartReplace(cmbOedema.Text) & "") & "" & _
                '             ", HandsArms=" & Trim(SmartReplace(txtHandsArms.Text) & "") & "" & _
                '             ", Nodes=" & Trim(SmartReplace(txtNodes.Text) & "") & "" & _
                '             ", Skin=" & Trim(SmartReplace(txtSkin.Text) & "") & "" & _
                '             ", BreastCondition=" & Trim(SmartReplace(txtBreastCondition.Text) & "") & "" & _
                '             ", Temperature=" & Val(txtTemperature.Text) & "" & _
                '             ", TemperatureUnits=" & Val(cmbTemperatureUnit.EditValue) & "" & _
                '             ", Height=" & Val(txtHeight.Text) & "" & _
                '             ", HeightUnitsId=" & Val(cmbHeightUnit.EditValue) & "" & _
                '             ", Weight=" & Val(txtWeight.Text) & "" & _
                '             ", WeightUnitsId=" & Val(cmbWeightUnit.EditValue) & "" & _
                '             ", AbdominalGirth=" & Val(txtAbdominalGirth.Text) & "" & _
                '             ", AbdominalGirthUnitsId=" & Val(cmbAbdominalGirthUnit.EditValue) & "" & _
                '             ", HeadCircumference=" & Val(txtHeadCircimference.Text) & "" & _
                '             ", HeadCircumferenceUnitsId=" & Val(cmbHeadCircumferenceUnit.EditValue)
                strQuery = "GeneralCondition=" & Trim(SmartReplace(txtGeneralCondition.Text) & "")
                strQuery = strQuery & ",Nutrition=" & Trim(SmartReplace(cmbNutrition.Text) & "")
                strQuery = strQuery & ", MucusMebrane1=" & Trim(SmartReplace(cmbMucus1.Text) & "")
                strQuery = strQuery & ",MucusMebrane2=" & Trim(SmartReplace(cmbMucus2.Text) & "")
                strQuery = strQuery & ", MucusMebrane3=" & Trim(SmartReplace(cmbMucus3.Text) & "")
                strQuery = strQuery & ", MucusMebrane4=" & Trim(SmartReplace(cmbMucus4.Text) & "")
                strQuery = strQuery & ", Hydration=" & Trim(SmartReplace(cmbHydration.Text) & "")
                strQuery = strQuery & ", Oedema=" & Trim(SmartReplace(cmbOedema.Text) & "")
                strQuery = strQuery & ", HandsArms=" & Trim(SmartReplace(txtHandsArms.Text) & "")
                strQuery = strQuery & ", Nodes=" & Trim(SmartReplace(txtNodes.Text) & "")
                strQuery = strQuery & ", Skin=" & Trim(SmartReplace(txtSkin.Text) & "")
                strQuery = strQuery & ", BreastCondition=" & Trim(SmartReplace(txtBreastCondition.Text) & "")
                If IsDBNullOrNothing(txtTemperature.Text) Then
                    strQuery = strQuery & ",Temperature=Null"
                Else
                    strQuery = strQuery & ", Temperature=" & Val(txtTemperature.Text)
                End If
                If IsDBNullOrNothing(cmbTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ", TemperatureUnits=Null"
                Else
                    strQuery = strQuery & ", TemperatureUnits=" & Val(cmbTemperatureUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtHeight.Text) Then
                    strQuery = strQuery & ", Height=Null"
                Else
                    strQuery = strQuery & ", Height=" & Val(txtHeight.Text)
                End If
                If IsDBNullOrNothing(cmbHeightUnit.EditValue) Then
                    strQuery = strQuery & ", HeightUnitsId=Null"
                Else
                    strQuery = strQuery & ", HeightUnitsId=" & Val(cmbHeightUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtWeight.Text) Then
                    strQuery = strQuery & ", Weight=Null"
                Else
                    strQuery = strQuery & ", Weight=" & Val(txtWeight.Text)
                End If
                If IsDBNullOrNothing(cmbWeightUnit.EditValue) Then
                    strQuery = strQuery & ", WeightUnitsId=Null"
                Else
                    strQuery = strQuery & ", WeightUnitsId=" & Val(cmbWeightUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtAbdominalGirth.Text) Then
                    strQuery = strQuery & ", AbdominalGirth=Null"
                Else
                    strQuery = strQuery & ", AbdominalGirth=" & Val(txtAbdominalGirth.Text)
                End If
                If IsDBNullOrNothing(cmbAbdominalGirthUnit.EditValue) Then
                    strQuery = strQuery & ", AbdominalGirthUnitsId=Null"
                Else
                    strQuery = strQuery & ", AbdominalGirthUnitsId=" & Val(cmbAbdominalGirthUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtHeadCircimference.Text) Then
                    strQuery = strQuery & ", HeadCircumference=Null"
                Else
                    strQuery = strQuery & ", HeadCircumference=" & Val(txtHeadCircimference.Text)
                End If
                If IsDBNullOrNothing(cmbHeadCircumferenceUnit.EditValue) Then
                    strQuery = strQuery & ", HeadCircumferenceUnitsId=Null"
                Else
                    strQuery = strQuery & ", HeadCircumferenceUnitsId=" & Val(cmbHeadCircumferenceUnit.EditValue)
                End If

                Call UpdateTable("tblVisitGeneralAssessment", strQuery, "VisitId=" & VisitId)
            Else
                strQuery = VisitId
                strQuery = strQuery & "," & Trim(SmartReplace(txtGeneralCondition.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbNutrition.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbMucus1.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbMucus2.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbMucus3.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbMucus4.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbHydration.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(cmbOedema.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(txtHandsArms.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(txtNodes.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(txtSkin.Text) & "")
                strQuery = strQuery & "," & Trim(SmartReplace(txtBreastCondition.Text) & "")
                If IsDBNullOrNothing(txtTemperature.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtTemperature.Text)
                End If
                If IsDBNullOrNothing(cmbTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(cmbTemperatureUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtHeight.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtHeight.Text)
                End If
                If IsDBNullOrNothing(cmbHeightUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(cmbHeightUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtWeight.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtWeight.Text)
                End If
                If IsDBNullOrNothing(cmbWeightUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(cmbWeightUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtAbdominalGirth.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtAbdominalGirth.Text)
                End If
                If IsDBNullOrNothing(cmbAbdominalGirthUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(cmbAbdominalGirthUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtHeadCircimference.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtHeadCircimference.Text)
                End If
                If IsDBNullOrNothing(cmbHeadCircumferenceUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(cmbHeadCircumferenceUnit.EditValue)
                End If
                Call InsertintoTable("tblVisitGeneralAssessment", strQuery)
            End If
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub


    'Private Sub btnGAssessmentROS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGAssessmentROS.Click
    '    Dim ROSForm As New frmReviewOfSystem(VisitId)
    '    ROSForm.Location = New Point(Me.Left + 464, Me.Top + 100) 'show this form at specific location on form
    '    ROSForm.ShowDialog()

    'End Sub

#End Region

#Region "Cardiology Page"

    Private Sub SaveCardio()
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitCardiology", "VisitCariologyId", "VisitId=" & VisitId))
            If Cnt > 0 Then
                strQuery = " Pulse=" & Trim(SmartReplace(txtPulse.Text) & "") & "" & _
                             ", PulseRhythm=" & Trim(SmartReplace(txtRhythm.Text) & "") & "" & _
                             ", PulseVolume=" & Trim(SmartReplace(txtVolume.Text) & "") & "" & _
                             ", JVPHeight=" & Trim(SmartReplace(txtJVPHeight.Text) & "") & "" & _
                             ", JVPWave=" & Trim(SmartReplace(txtJVPWave.Text) & "") & "" & _
                             ", HeartInspection=" & Trim(SmartReplace(txtHeartInspection.Text) & "") & "" & _
                             ", ApexPosition=" & Trim(SmartReplace(txtApexPosition.Text) & "") & "" & _
                             ", ApexCharacter=" & Trim(SmartReplace(txtApexCharacter.Text) & "") & "" & _
                             ", Thrill=" & Trim(SmartReplace(txtThrill.Text) & "") & "" & _
                             ", S1=" & Trim(SmartReplace(txtS1.Text) & "") & "" & _
                             ", S2=" & Trim(SmartReplace(txtS2.Text) & "") & "" & _
                             ", AddedSound=" & Trim(SmartReplace(txtAddedSound.Text) & "") & "" & _
                             ", Murmurs=" & Trim(SmartReplace(txtMurmurs.Text) & "") & "" & _
                             ", Arterial=" & Trim(SmartReplace(txtArterial.Text) & "") & "" & _
                             ", Venous=" & Trim(SmartReplace(txtVenous.Text) & "") & ""
                Call UpdateTable("tblVisitCardiology", strQuery, "VisitId=" & VisitId)
                If IsDBNullOrNothing(txtBPSupineS.Text) Then
                    strQuery = " BPSupineS=Null"
                Else
                    strQuery = " BPSupineS=" & Val(txtBPSupineS.Text)
                End If
                If IsDBNullOrNothing(txtBPSupineD.Text) Then
                    strQuery = strQuery & ",BPSupineD=Null"
                Else
                    strQuery = strQuery & ",BPSupineD=" & Val(txtBPSupineD.Text)
                End If
                If IsDBNullOrNothing(txtBPSittingS.Text) Then
                    strQuery = strQuery & ",BPSittingS=Null"
                Else
                    strQuery = strQuery & ",BPSittingS=" & Val(txtBPSittingS.Text)
                End If
                If IsDBNullOrNothing(txtBPSittingD.Text) Then
                    strQuery = strQuery & ",BPSittingD=Null"
                Else
                    strQuery = strQuery & ",BPSittingD=" & Val(txtBPSittingD.Text)
                End If
                If IsDBNullOrNothing(txtBPStandingS.Text) Then
                    strQuery = strQuery & ",BPStandingS=Null"
                Else
                    strQuery = strQuery & ",BPStandingS=" & Val(txtBPStandingS.Text)
                End If
                If IsDBNullOrNothing(txtBPStandingD.Text) Then
                    strQuery = strQuery & ",BPStandingD=Null"
                Else
                    strQuery = strQuery & ",BPStandingD=" & Val(txtBPStandingD.Text)
                End If

                Call UpdateTable("tblVisitBPPulse", strQuery, "VisitId=" & VisitId)
            Else
                strQuery = VisitId & _
                            "," & Trim(SmartReplace(txtPulse.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtRhythm.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtVolume.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtJVPHeight.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtJVPWave.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtHeartInspection.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtApexPosition.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtApexCharacter.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtThrill.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtS1.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtS2.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtAddedSound.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtMurmurs.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtArterial.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtVenous.Text) & "") & ""
                Call InsertintoTable("tblVisitCardiology", strQuery)


                '"," & Val(txtBPSupineS.Text) & _
                '"," & Val(txtBPSupineD.Text) & _
                '"," & Val(txtBPSittingS.Text) & _
                '"," & Val(txtBPSittingD.Text) & _
                '"," & Val(txtBPStandingS.Text) & _
                '"," & Val(txtBPStandingD.Text) & _
                '",Null,Null,Null"
                strQuery = VisitId
                If IsDBNullOrNothing(txtBPSupineS.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPSupineS.Text)
                End If
                If IsDBNullOrNothing(txtBPSupineD.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPSupineD.Text)
                End If
                If IsDBNullOrNothing(txtBPSittingS.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPSittingS.Text)
                End If
                If IsDBNullOrNothing(txtBPSittingD.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPSittingD.Text)
                End If
                If IsDBNullOrNothing(txtBPStandingS.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPStandingS.Text)
                End If
                If IsDBNullOrNothing(txtBPStandingD.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPStandingD.Text)
                End If
                strQuery = strQuery & ",Null,Null,Null"
                Call InsertintoTable("tblVisitBPPulse", strQuery)
            End If
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

#End Region

#Region "Mental Page"


    Private Sub SaveMental()
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitMental", "VisitMentalId", "VisitId=" & VisitId))
            If Cnt > 0 Then
                strQuery = " GeneralAppearence=" & Trim(SmartReplace(txtGeneralAppearance.Text) & "") & "" & _
                            ", ThoughtProcess=" & Trim(SmartReplace(txtThoughtProcess.Text) & "") & "" & _
                            ", Mood=" & Trim(SmartReplace(txtMood.Text) & "") & "" & _
                            ", Delusion=" & Trim(SmartReplace(txtDelusion.Text) & "") & "" & _
                            ", Hallucinations=" & Trim(SmartReplace(txtHallucinations.Text) & "") & "" & _
                            ", Obsessions=" & Trim(SmartReplace(txtObsessions.Text) & "") & "" & _
                            ", Orientation=" & Trim(SmartReplace(txtOrientation.Text) & "") & "" & _
                            ", Memory=" & Trim(SmartReplace(txtMemory.Text) & "") & "" & _
                            ", AttentionConcentration=" & Trim(SmartReplace(txtAttentionConcentration.Text) & "") & "" & _
                            ", GeneralInformation=" & Trim(SmartReplace(txtGeneralInformation.Text) & "") & "" & _
                            ", Intelligence=" & Trim(SmartReplace(txtIntelligence.Text) & "") & "" & _
                            ", InsightJudgement=" & Trim(SmartReplace(txtInsightJudgement.Text) & "") & "" & _
                            ", Speech=" & Trim(SmartReplace(txtSpeech.Text) & "") & ""
                Call UpdateTable("tblVisitMental", strQuery, "VisitId=" & VisitId)

            Else
                strQuery = VisitId & _
                            "," & Trim(SmartReplace(txtGeneralAppearance.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtThoughtProcess.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtMood.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtDelusion.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtHallucinations.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtObsessions.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtOrientation.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtMemory.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtAttentionConcentration.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtGeneralInformation.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtIntelligence.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtInsightJudgement.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtSpeech.Text) & "") & ""
                Call InsertintoTable("tblVisitMental", strQuery)

            End If
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub


#End Region

#Region "GastroIntestinal Page"

    Private Sub SaveGastroIntestinal()
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitGastroIntestinal", "VisitGastroIntestinalId", "VisitId=" & VisitId))
            If Cnt > 0 Then
                strQuery = " Mouth=" & Trim(SmartReplace(txtMouth.Text) & "") & "" & _
                            ", AbdomenInspection=" & Trim(SmartReplace(txtAbodmenInspection.Text) & "") & "" & _
                            ", AbdomenPalpitation=" & Trim(SmartReplace(txtAbdomenPalpitation.Text) & "") & "" & _
                            ", AbdomenPercussion=" & Trim(SmartReplace(txtAbdomenPercussion.Text) & "") & "" & _
                            ", AbdomenAuscultation=" & Trim(SmartReplace(txtAbdomenAuscultation.Text) & "") & "" & _
                            ", Rectum=" & Trim(SmartReplace(txtRectum.Text) & "") & "" & _
                            ", Anus=" & Trim(SmartReplace(txtAnus.Text) & "") & ""

                Call UpdateTable("tblVisitGastroIntestinal", strQuery, "VisitId=" & VisitId)

            Else
                strQuery = VisitId & _
                           "," & Trim(SmartReplace(txtMouth.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtAbodmenInspection.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtAbdomenPalpitation.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtAbdomenPercussion.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtAbdomenAuscultation.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtRectum.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtAnus.Text) & "") & ""
                Call InsertintoTable("tblVisitGastroIntestinal", strQuery)

            End If
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

#End Region

#Region "GenitoUrinary Page"


    Private Sub SaveGenitoUrinary()
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitGenitoUrinary", "VisitGenitoUrinary", "VisitId=" & VisitId))
            If Cnt > 0 Then
                strQuery = " GentitaliaInspection=" & Trim(SmartReplace(txtGenitaliaInspection.Text) & "") & "" & _
                            ",GentitaliaPalpitation=" & Trim(SmartReplace(txtGenitaliaPalpitation.Text) & "")

                Call UpdateTable("tblVisitGenitoUrinary", strQuery, "VisitId=" & VisitId)

            Else
                strQuery = VisitId & _
                           "," & Trim(SmartReplace(txtGenitaliaInspection.Text) & "") & "" & _
                           "," & Trim(SmartReplace(txtGenitaliaPalpitation.Text) & "") & _
                           ",Null,Null,Null"
                Call InsertintoTable("tblVisitGenitoUrinary", strQuery)

            End If
            'Save urine samples 
            Dim e As New EventArgs


            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
            UrineTestForm.btnSave_Click(UrineTestForm.btnSave, e)
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

#End Region

#Region "Respiratory Page"



    Private Sub SaveRespiratory()
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitRespiratory", "VisitRespiratoryId", "VisitId=" & VisitId))

            If Cnt > 0 Then
                strQuery = " Cough=" & Trim(SmartReplace(txtCough.Text) & "") & "" & _
                             ", Sputum=" & Trim(SmartReplace(txtSputum.Text) & "") & "" & _
                             ", RespiratoryEffort=" & Trim(SmartReplace(txtRepiratoryEffort.Text) & "") & "" & _
                             ", Nose=" & Trim(SmartReplace(txtNose.Text) & "") & "" & _
                             ", Sinuses=" & Trim(SmartReplace(txtSinuses.Text) & "") & "" & _
                             ", Tonsils=" & Trim(SmartReplace(txtTonsils.Text) & "") & "" & _
                             ", Pharnyx=" & Trim(SmartReplace(txtPharnyx.Text) & "") & "" & _
                             ", Trachea=" & Trim(SmartReplace(txtTrachea.Text) & "") & "" & _
                             ", ChestInspection=" & Trim(SmartReplace(txtChestInspection.Text) & "") & "" & _
                             ", ChestPalpitation=" & Trim(SmartReplace(txtChestPalpitation.Text) & "") & "" & _
                             ", ChestPercussion=" & Trim(SmartReplace(txtChestPercussion.Text) & "") & "" & _
                             ", ChestAuscultation=" & Trim(SmartReplace(txtChestAuscultation.Text) & "") & ""
                If IsDBNullOrNothing(txtRespiratoryRate.Text) Then
                    strQuery = strQuery & ", RespiratoryRate=Null"
                Else
                    strQuery = strQuery & ", RespiratoryRate=" & Val(txtRespiratoryRate.Text)
                End If
                strQuery = strQuery & ", Ear =" & Trim(SmartReplace(txtEar.Text) & "") & ""

                Call UpdateTable("tblVisitRespiratory", strQuery, "VisitId=" & VisitId)

            Else
                strQuery = VisitId & _
                          "," & Trim(SmartReplace(txtCough.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtSputum.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtRepiratoryEffort.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtNose.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtSinuses.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtTonsils.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtPharnyx.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtTrachea.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtChestInspection.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtChestPalpitation.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtChestPercussion.Text) & "") & "" & _
                             "," & Trim(SmartReplace(txtChestAuscultation.Text) & "") & ""
                If IsDBNullOrNothing(txtRespiratoryRate.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtRespiratoryRate.Text)
                End If
                strQuery = strQuery & "," & Trim(SmartReplace(txtEar.Text) & "") & ""

                Call InsertintoTable("tblVisitRespiratory", strQuery)

            End If
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

#End Region

#Region "Locomotion Page"

    Private Sub SaveLocomotion()
        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitLocomotion", "VisitLocomotionId", "VisitId=" & VisitId))
            If Cnt > 0 Then
                strQuery = " Spine=" & Trim(SmartReplace(txtSpine.Text) & "") & "" & _
                            ", Joints=" & Trim(SmartReplace(txtJoints.Text) & "") & "" & _
                            ", Muscles=" & Trim(SmartReplace(txtMuscles.Text) & "") & "" & _
                            ", Bones=" & Trim(SmartReplace(txtBones.Text) & "") & "" & _
                            ", Gait=" & Trim(SmartReplace(txtGait.Text) & "") & ""
                Call UpdateTable("tblVisitLocomotion", strQuery, "VisitId=" & VisitId)

            Else
                strQuery = VisitId & _
                          "," & Trim(SmartReplace(txtSpine.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtJoints.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtMuscles.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtBones.Text) & "") & "" & _
                            "," & Trim(SmartReplace(txtGait.Text) & "") & ""

                Call InsertintoTable("tblVisitLocomotion", strQuery)

            End If
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


#End Region

#Region "Diagnosis Page"

    Private Sub PopulateActiveGrid()
        Dim strQuery As String
        Try
            Call SetActiveEditorDataColumn()
            strQuery = "SELECT tblVisitDiagnosis.VisitDiagnosisId as [ID],tblVisitDiagnosis.DiagnosisId as Diagnosis,tblVisitDiagnosis.DiagnosisSeverityId as [DiagnosisSeverity],DiagnosisDate as [DiagnosisDate],Active FROM ( (tblVisitDiagnosis JOIN LtblDiagnosis ON tblVisitDiagnosis.DiagnosisId = LtblDiagnosis.DiagnosisId ) LEFT OUTER JOIN  LtblDiagnosisSeverity ON tblVisitDiagnosis.DiagnosisSeverityId=LtblDiagnosisSeverity.DiagnosisSeverityId) JOIN tblVisits ON  tblVisitDiagnosis.VisitId=tblVisits.VisitId  WHERE tblVisits.PatientId =" & PatientId & " AND Active=1  AND PracticeId=" & GetPracticeId(gintUserID)
            Dim dsTemp As DataSet = FillDataSet(strQuery)
            With grdActive
                .BeginUpdate()
                .DataSource = dsTemp.Tables(0)
                .EndUpdate()
            End With

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub InitialiseActiveDataEntry()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("Active")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("Diagnosis", GetType(Integer))
            .Add("DiagnosisSeverity", GetType(Integer))
            .Add("DiagnosisDate", GetType(Date))
            .Add("Active", GetType(Boolean))
        End With
        grdActive.DataSource = dtTemp
        gdvActive.Columns("ID").Visible = False
        gdvActive.Columns("Active").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetActiveEditorDataColumn()
        Try
            Call InitialiseActiveDataEntry()
            Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvActive
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                .Columns("Diagnosis").AppearanceHeader.Font = fnBold
                .Columns("Diagnosis").Width = 100
                .Columns("DiagnosisDate").AppearanceHeader.Font = fnBold
                .Columns("DiagnosisDate").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("DiagnosisDate").DisplayFormat.FormatString = gstrDtFormat
                .Columns("DiagnosisDate").Width = 100
                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpglkActiveDiagnosis = New RepositoryItemGridLookUpEdit()
            Dim DiagnosisNameSize As Size
            DiagnosisNameSize.Width = 500
            DiagnosisNameSize.Height = 40
            Dim dsTemp As DataSet = FillDataSet("select DiagnosisId,Diagnosis,DiagnosisNumber from LtblDiagnosis order by Diagnosis")
            With rpglkActiveDiagnosis
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "Diagnosis"
                .ValueMember = "DiagnosisId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DiagnosisId").Visible = False
                .View.Columns("DiagnosisNumber").Visible = False
                .PopupFormMinSize = DiagnosisNameSize

            End With
            dsTemp.Dispose()

            rpglkActiveSeverity = New RepositoryItemGridLookUpEdit()
            Dim SeverityNameSize As Size
            SeverityNameSize.Width = 500
            SeverityNameSize.Height = 40
            Dim dsTemp1 As DataSet = FillDataSet("select DiagnosisSeverityId,DiagnosisSeverity from LtblDiagnosisSeverity order by DiagnosisSeverity")
            With rpglkActiveSeverity
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp1.Tables(0)
                .DisplayMember = "DiagnosisSeverity"
                .ValueMember = "DiagnosisSeverityId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DiagnosisSeverityId").Visible = False
                .PopupFormMinSize = SeverityNameSize

            End With
            dsTemp.Dispose()

            rpdtActiveDiagnosisDate = New RepositoryItemDateEdit
            With rpdtActiveDiagnosisDate
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .EditFormat.FormatString = gstrDtFormat
                .Mask.UseMaskAsDisplayFormat = True
            End With

            grdActive.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpglkActiveDiagnosis, rpglkActiveSeverity, rpdtActiveDiagnosisDate})
            With gdvActive
                .Columns("Diagnosis").ColumnEdit = rpglkActiveDiagnosis
                '.Columns("Stock").ColumnEdit = rptxtStock
                .Columns("DiagnosisSeverity").ColumnEdit = rpglkActiveSeverity
                .Columns("DiagnosisDate").ColumnEdit = rpdtActiveDiagnosisDate

                '.Columns("Remarks").ColumnEdit = rptxtremarks
                '.OptionsView.ShowFooter = True
                ' .Columns("Diagnosis").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub InitialiseInActiveDataEntry()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("InActive")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("Diagnosis", GetType(Integer))
            .Add("DiagnosisSeverity", GetType(Integer))
            .Add("DiagnosisDate", GetType(Date))
            .Add("Active", GetType(Boolean))
            .Add("Resolve Date", GetType(Date))
        End With
        grdInactive.DataSource = dtTemp
        gdvInactive.Columns("ID").Visible = False
        gdvInactive.Columns("Active").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetInActiveEditorDataColumn()
        Try
            Call InitialiseInActiveDataEntry()
            Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvInactive
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                .Columns("Diagnosis").AppearanceHeader.Font = fnBold
                .Columns("Diagnosis").Width = 100
                .Columns("DiagnosisDate").AppearanceHeader.Font = fnBold
                .Columns("DiagnosisDate").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("DiagnosisDate").DisplayFormat.FormatString = gstrDtFormat
                .Columns("DiagnosisDate").Width = 100

                .Columns("Resolve Date").AppearanceHeader.Font = fnBold
                .Columns("Resolve Date").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .Columns("Resolve Date").DisplayFormat.FormatString = gstrDtFormat
                .Columns("Resolve Date").Width = 100
                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpglkInActiveDiagnosis = New RepositoryItemGridLookUpEdit()
            Dim DiagnosisNameSize As Size
            DiagnosisNameSize.Width = 500
            DiagnosisNameSize.Height = 40
            Dim dsTemp As DataSet = FillDataSet("select DiagnosisId,Diagnosis,DiagnosisNumber from LtblDiagnosis order by Diagnosis")
            With rpglkInActiveDiagnosis
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "Diagnosis"
                .ValueMember = "DiagnosisId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DiagnosisId").Visible = False
                .View.Columns("DiagnosisNumber").Visible = False
                .PopupFormMinSize = DiagnosisNameSize

            End With
            dsTemp.Dispose()

            rpglkInActiveSeverity = New RepositoryItemGridLookUpEdit()
            Dim SeverityNameSize As Size
            SeverityNameSize.Width = 500
            SeverityNameSize.Height = 40
            Dim dsTemp1 As DataSet = FillDataSet("select DiagnosisSeverityId,DiagnosisSeverity from LtblDiagnosisSeverity order by DiagnosisSeverity")
            With rpglkInActiveSeverity
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp1.Tables(0)
                .DisplayMember = "DiagnosisSeverity"
                .ValueMember = "DiagnosisSeverityId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DiagnosisSeverityId").Visible = False
                .PopupFormMinSize = SeverityNameSize

            End With
            dsTemp.Dispose()

            rpdtInActiveDiagnosisDate = New RepositoryItemDateEdit
            With rpdtActiveDiagnosisDate
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .EditFormat.FormatString = gstrDtFormat
                .Mask.UseMaskAsDisplayFormat = True
            End With

            rpdtInActiveResolveDate = New RepositoryItemDateEdit
            With rpdtInActiveResolveDate
                .Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .DisplayFormat.FormatString = gstrDtFormat
                .EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime
                .EditFormat.FormatString = gstrDtFormat
                .Mask.UseMaskAsDisplayFormat = True
            End With

            grdInactive.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpglkInActiveDiagnosis, rpglkInActiveSeverity, rpdtInActiveDiagnosisDate, rpdtInActiveResolveDate})
            With gdvInactive
                .Columns("Diagnosis").ColumnEdit = rpglkInActiveDiagnosis
                '.Columns("Stock").ColumnEdit = rptxtStock
                .Columns("DiagnosisSeverity").ColumnEdit = rpglkInActiveSeverity
                .Columns("DiagnosisDate").ColumnEdit = rpdtInActiveDiagnosisDate
                .Columns("Resolve Date").ColumnEdit = rpdtInActiveResolveDate

                '.Columns("Remarks").ColumnEdit = rptxtremarks
                '.OptionsView.ShowFooter = True
                ' .Columns("Diagnosis").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub PopulateInactiveGrid()
        Dim strQuery As String
        Try
            Call SetInActiveEditorDataColumn()
            strQuery = "SELECT tblVisitDiagnosis.VisitDiagnosisId as [ID],tblVisitDiagnosis.DiagnosisId as Diagnosis,tblVisitDiagnosis.DiagnosisSeverityId as [DiagnosisSeverity],DiagnosisDate as [DiagnosisDate],Active,ResolveDate as [Resolve Date] FROM ( (tblVisitDiagnosis JOIN LtblDiagnosis ON tblVisitDiagnosis.DiagnosisId = LtblDiagnosis.DiagnosisId ) LEFT OUTER JOIN  LtblDiagnosisSeverity ON tblVisitDiagnosis.DiagnosisSeverityId=LtblDiagnosisSeverity.DiagnosisSeverityId) JOIN tblVisits ON  tblVisitDiagnosis.VisitId=tblVisits.VisitId  WHERE tblVisits.PatientId =" & PatientId & " AND Active=0 AND PracticeId=" & GetPracticeId(gintUserID)
            Dim dsTemp As DataSet = FillDataSet(strQuery)
            With grdInactive
                .BeginUpdate()
                .DataSource = dsTemp.Tables(0)
                .EndUpdate()
            End With

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub SaveDiagnosis()


        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Dim intCtr As Integer
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Call DeleteFromTable("tblVisitDiagnosis", "VisitId=" & VisitId)
            For intCtr = 0 To gdvActive.RowCount - 1
                If Val(Trim(gdvActive.GetRowCellValue(intCtr, "Diagnosis") & "")) <= 0 Then Continue For
                strQuery = Val(gdvActive.GetRowCellValue(intCtr, "Diagnosis")) & _
                            ",'" & strRecordID("LtblDiagnosis", "Diagnosis", "DiagnosisId=" & Val(gdvActive.GetRowCellValue(intCtr, "Diagnosis"))) & "'" & _
                            "," & gdvActive.GetRowCellValue(intCtr, "DiagnosisSeverity") & _
                            "," & VisitId & _
                            ",'" & Format(gdvActive.GetRowCellValue(intCtr, "DiagnosisDate"), gstrDtFormat) & "'" & _
                            ",1" & _
                            ",Null"
                Call InsertintoTable("tblVisitDiagnosis", strQuery)
            Next

            For intCtr = 0 To gdvInactive.RowCount - 1
                If Val(Trim(gdvInactive.GetRowCellValue(intCtr, "Diagnosis") & "")) <= 0 Then Continue For
                strQuery = Val(gdvInactive.GetRowCellValue(intCtr, "Diagnosis")) & _
                            ",'" & strRecordID("LtblDiagnosis", "Diagnosis", "DiagnosisId=" & Val(gdvInactive.GetRowCellValue(intCtr, "Diagnosis"))) & "'" & _
                            "," & gdvInactive.GetRowCellValue(intCtr, "DiagnosisSeverity") & _
                            "," & VisitId & _
                            ",'" & Format(gdvInactive.GetRowCellValue(intCtr, "DiagnosisDate"), gstrDtFormat) & "'" & _
                            ",1" & _
                            ",'" & Format(gdvInactive.GetRowCellValue(intCtr, "ResolveDate"), gstrDtFormat) & "'"
                Call InsertintoTable("tblVisitDiagnosis", strQuery)
            Next
            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try


    End Sub



    'Private Sub dgdActive_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgdActive.Click
    '    Dim dtActive As DataTable = dgdActive.DataSource
    '    If dtActive.Rows.Count = 0 Then 'no rows
    '        Exit Sub                    'so exit  
    '    End If
    '    Dim RowNumber As Integer = dgdActive.CurrentCell.RowNumber 'this is row, which may be deleted or inserted into other row

    '    If dgdActive.CurrentCell.ColumnNumber = 5 Then
    '        'change the state of checkbox (toggle)
    '        dgdActive.Item(dgdActive.CurrentCell) = Not dgdActive.Item(dgdActive.CurrentCell)

    '        If dgdActive.Item(dgdActive.CurrentCell) = False Then
    '            Dim dtInactive As DataTable = dgdInactive.DataSource
    '            Dim rowInactive As DataRow = dtInactive.NewRow

    '            rowInactive.Item("DiagnosisId") = dgdActive.Item(RowNumber, 0)
    '            rowInactive.Item("Diagnosis") = dgdActive.Item(RowNumber, 1)
    '            rowInactive.Item("DiagnosisSeverityId") = dgdActive.Item(RowNumber, 2)
    '            rowInactive.Item("Severity") = dgdActive.Item(RowNumber, 3)
    '            rowInactive.Item("DiagnosisDate") = dgdActive.Item(RowNumber, 4)
    '            rowInactive.Item("Active") = 0
    '            rowInactive.Item("ResolveDate") = Now
    '            dtInactive.Rows.Add(rowInactive)
    '            dgdInactive.DataSource = dtInactive

    '            'remove this row from active datagrid
    '            dtActive.Rows.RemoveAt(RowNumber)
    '            dgdActive.DataSource = dtActive

    '        End If
    '    End If


    'End Sub

    'Private Sub dgdInactive_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgdInactive.Click
    '    Dim dtInactive As DataTable = dgdInactive.DataSource  'this is row, which may be deleted or inserted into other row
    '    If dtInactive.Rows.Count = 0 Then 'no row
    '        Exit Sub                      'exit sub
    '    End If
    '    Dim RowNumber As Integer = dgdInactive.CurrentCell.RowNumber 'take data from this row,add it to active problem's gridrow

    '    If dgdInactive.CurrentCell.ColumnNumber = 5 Then
    '        'change the state of checkbox (toggle)
    '        dgdInactive.Item(dgdInactive.CurrentCell) = Not dgdInactive.Item(dgdInactive.CurrentCell)

    '        If dgdInactive.Item(dgdInactive.CurrentCell) = True Then
    '            Dim dtActive As DataTable = dgdActive.DataSource
    '            Dim rowActive As DataRow = dtActive.NewRow

    '            rowActive.Item("DiagnosisId") = dgdInactive.Item(RowNumber, 0)
    '            rowActive.Item("Diagnosis") = dgdInactive.Item(RowNumber, 1)
    '            rowActive.Item("DiagnosisSeverityId") = dgdInactive.Item(RowNumber, 2)
    '            rowActive.Item("Severity") = dgdInactive.Item(RowNumber, 3)
    '            rowActive.Item("DiagnosisDate") = dgdInactive.Item(RowNumber, 4)
    '            rowActive.Item("Active") = 1

    '            dtActive.Rows.Add(rowActive)
    '            dgdActive.DataSource = dtActive

    '            'remove this row from inactive datagrid
    '            dtInactive.Rows.RemoveAt(RowNumber)
    '            dgdInactive.DataSource = dtInactive

    '        End If
    '    End If

    'End Sub


#End Region

#Region "Summary Page"
    Private Sub PopulateSummaryLookups()

        PopulateLookupDX(lkAssessment, "Diagnosis", "DiagnosisId", "LtblDiagnosis", "DiagnosisId,Diagnosis", , "Diagnosis", True)
        PopulateLookupDX(lkSeverity, "DiagnosisSeverity", "DiagnosisSeverityId", "LtblDiagnosisSeverity", "DiagnosisSeverityId,DiagnosisSeverity", , "DiagnosisSeverity", True)

        PopulateLookupDX(lkBloodSugar, "BloodSugarUnit", "BloodSugarID", "LtblUnitsBloodSugar", "BloodSugarID,BloodSugarUnit", "", "BloodSugarUnit")
        'lkBloodSugar.ItemIndex = 0
        PopulateLookupDX(lkTemperatureUnit, "TempUnit", "TempUnitId", "LtblUnitsTemp", "TempUnitId,TempUnit", "", "TempUnit")
        'lkTemperatureUnit.ItemIndex = 1
        'PopulateList(lstSpecialists, "SELECT DoctorId,(Firstname + ' ' + Lastname) as Name FROM tblSpecialists ORDER BY Name", "Name", "DoctorId")
        Call PopulateCheckedListboxDX(lstReferrals, "Name", "DoctorId", "tblSpecialists", "DoctorId,(Firstname + ' ' + Lastname) as Name", , "Name")
    End Sub

    Private Function IsValidSummaryEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidSummaryEntry = False

        If Not IsDBNullOrNothing(txtR.Text) Then
            If Val(txtR.EditValue) <= 0 Then
                strMsg = "Please enter valid Respiratory Rate."
                txtR.Focus()
                txtR.SelectAll()
            End If
        End If

        'Check for valid temparature
        If Not IsDBNullOrNothing(txtT.Text) Then
            If Val(txtT.EditValue & "") <= 0 Then
                strMsg = "Please enter proper Temperature."
                txtT.Focus()
                txtT.SelectAll()
            End If
        End If
        If Trim(strMsg) <> "" Then
            IsValidSummaryEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            IsValidSummaryEntry = True
        End If
    End Function

    Private Sub saveSummaryTab()
        Dim blnIsTransactionOpen As Boolean

        Try

            If IsValidSummaryEntry() = False Then
                Exit Sub
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            'Save PC and History
            Call SaveSummaryPresentHistory()
            'Save VisitSummary data.
            Call SaveVisitSummary()
            'Save Respiratory rate
            Call SaveSummaryRespiratory()
            'Save Temparature
            Call SaveTemparature()
            'Save Pulse
            Call SavePulse()
            'Save BloodSugar
            Call SaveBloodSugar()
            'Save Invectigative (Other Test).
            Call SaveInv()
            'Save Treatment (Therapeutic)
            Call SaveTreatment()
            'Save Refferals
            Call SaveSummaryRefferals()
            'Save BP
            Call SaveBP()
            If Val(lkAssessment.EditValue) > 0 Then
                Dim AssessmentID As Integer = Val(strRecordID("tblVisitDiagnosis", "DiagnosisId", "VisitId=" & VisitId & " and DiagnosisId=" & Val(lkAssessment.EditValue)))
                If AssessmentID > 0 Then
                    'MessageBox.Show("This Assessment details already exists on this visit.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    'lkAssessment.Focus()
                    'Exit Sub
                    Dim strQuery As String
                    If IsDBNullOrNothing(lkSeverity.EditValue) Then
                        strQuery = "DiagnosisSeverityId=Null"
                    Else
                        strQuery = "DiagnosisSeverityId=" & Val(lkSeverity.EditValue)
                    End If
                    Call UpdateTable("tblVisitDiagnosis", strQuery, "VisitId=" & VisitId & " and DiagnosisId=" & lkAssessment.EditValue)
                Else
                    Dim strFeilds As String = "tblVisitDiagnosis(DiagnosisId,Diagnosis,DiagnosisSeverityId,VisitId,DiagnosisDate,Active,ResolveDate)"
                    Dim strQuery As String = lkAssessment.EditValue & ",'" & lkAssessment.Text & "'," & IIf(IsDBNullOrNothing(lkSeverity.EditValue) = True, "NULL", lkSeverity.EditValue) & "," & VisitId & " ,'" & DateTime.Today & "',1,NULL"
                    'Add selected Diagnosis into database and Disable combos.
                    Call InsertintoTable(strFeilds, strQuery)

                End If
            End If

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub SaveSummaryPresentHistory()
        Dim strQuery As String

        Try
            strQuery = "PresentingComplaint=" & SmartReplace(txtPC.Text) & ", History=" & SmartReplace(txtSummaryHistory.Text)
            Call UpdateTable("tblVisits", strQuery, "VisitId=" & VisitId)

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveVisitSummary()
        Cursor.Current = Cursors.WaitCursor
        'Patient is already registered ,so there is no need to check wheather visitId exist or not
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitSummary", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitSummary(VisitId, Gen, ENT, RS, CVS, Abd, Mu_SK, NS)"
                strQuery = VisitId & "," & _
                            SmartReplace(txtGen.EditValue) & "," & _
                            SmartReplace(txtENT.EditValue) & "," & _
                            SmartReplace(txtRS.EditValue) & "," & _
                            SmartReplace(txtCVS.EditValue) & "," & _
                            SmartReplace(txtAbd.EditValue) & "," & _
                            SmartReplace(txtMu_SK.EditValue) & "," & _
                            SmartReplace(txtNS.EditValue)

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Gen=" & SmartReplace(txtGen.EditValue)
                strQuery = strQuery & ",ENT=" & SmartReplace(txtENT.EditValue)
                strQuery = strQuery & ",RS=" & SmartReplace(txtRS.EditValue)
                strQuery = strQuery & ",CVS=" & SmartReplace(txtCVS.EditValue)
                strQuery = strQuery & ",Abd=" & SmartReplace(txtAbd.EditValue)
                strQuery = strQuery & ",Mu_SK=" & SmartReplace(txtMu_SK.EditValue)
                strQuery = strQuery & ",NS=" & SmartReplace(txtNS.EditValue)

                Call UpdateTable("tblVisitSummary", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveSummaryRespiratory()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitRespiratory", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitRespiratory( VisitId,RespiratoryRate)"
                strQuery = VisitId & "," & Val(txtR.EditValue & "")

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "RespiratoryRate=" & Val(txtR.EditValue & "")

                Call UpdateTable("tblVisitRespiratory", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveTemparature()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitGeneralAssessment", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitGeneralAssessment(VisitId,Temperature,TemperatureUnits)"

                strQuery = VisitId
                If IsDBNullOrNothing(txtT.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtT.Text)
                End If
                If IsDBNullOrNothing(lkTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(lkTemperatureUnit.EditValue)
                End If
                Call InsertintoTable(strFeilds, strQuery)
            Else
                If IsDBNullOrNothing(txtT.Text) Then
                    strQuery = "Temperature=Null"
                Else
                    strQuery = "Temperature=" & Val(txtT.EditValue)
                End If
                If IsDBNullOrNothing(lkTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ",TemperatureUnits=Null"
                Else
                    strQuery = strQuery & ",TemperatureUnits=" & Val(lkTemperatureUnit.EditValue)
                End If

                Call UpdateTable("tblVisitGeneralAssessment", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SavePulse()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitCardiology", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitCardiology(VisitId,Pulse)"

                strQuery = VisitId
                If IsDBNullOrNothing(txtP.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtP.Text)
                End If

                Call InsertintoTable(strFeilds, strQuery)
            Else
                If IsDBNullOrNothing(txtP.Text) Then
                    strQuery = "Pulse=Null"
                Else
                    strQuery = "Pulse=" & Val(txtP.EditValue & "")
                End If
                Call UpdateTable("tblVisitCardiology", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveBP()
        Cursor.Current = Cursors.WaitCursor
        'Save Respiratory rate
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitBPPulse", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitBPPulse(VisitId,BPSupineS,BPSupineD)"

                strQuery = VisitId
                If IsDBNullOrNothing(txtBPSupineS.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPSupineS.Text)
                End If
                If IsDBNullOrNothing(txtBPSupineD.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBPSupineD.Text)
                End If
                Call InsertintoTable(strFeilds, strQuery)
            Else
                If IsDBNullOrNothing(txtBPSupineS.Text) Then
                    strQuery = "BPSupineS=Null"
                Else
                    strQuery = "BPSupineS=" & Val(txtBPSupineS.EditValue)
                End If
                If IsDBNullOrNothing(txtBPSupineD.Text) Then
                    strQuery = strQuery & ",BPSupineD =Null"
                Else
                    strQuery = strQuery & ",BPSupineD =" & Val(txtBPSupineD.Text)
                End If
                Call UpdateTable("tblVisitBPPulse", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveBloodSugar()
        Cursor.Current = Cursors.WaitCursor
        'Save Blood Sugar
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitGenitoUrinary", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitGenitoUrinary(VisitId,BloodSugar,BloodSugarUnit,Urine)"
                strQuery = VisitId
                If IsDBNullOrNothing(txtBloodSugar.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(txtBloodSugar.EditValue)
                End If
                If IsDBNullOrNothing(lkBloodSugar.EditValue) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Val(lkBloodSugar.EditValue)
                End If
                If IsDBNullOrNothing(txtUrine.Text) Then
                    strQuery = strQuery & ",Null"
                Else
                    strQuery = strQuery & "," & Trim(SmartReplace(txtUrine.Text) & "")
                End If
                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "BloodSugar=" & Val(txtBloodSugar.EditValue & "")
                If IsDBNullOrNothing(lkBloodSugar.EditValue) Then
                    strQuery = strQuery & ",BloodSugarUnit=Null"
                Else
                    strQuery = strQuery & ",BloodSugarUnit=" & Val(lkBloodSugar.EditValue)
                End If
                If IsDBNullOrNothing(txtUrine.Text) Then
                    strQuery = strQuery & ",Urine=Null"
                Else
                    strQuery = strQuery & ",Urine=" & SmartReplace(txtUrine.Text)
                End If
                Call UpdateTable("tblVisitGenitoUrinary", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveTreatment()
        Cursor.Current = Cursors.WaitCursor
        'Save Treatment
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitResult", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitResult(VisitId,Therapy,Hospitalised)"

                strQuery = VisitId & "," & SmartReplace(txtTreatment.EditValue) & ",0"

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Therapy=" & SmartReplace(txtTreatment.EditValue)

                Call UpdateTable("tblVisitResult", strQuery, " VisitId=" & VisitId)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveInv()
        Cursor.Current = Cursors.WaitCursor
        Dim strQuery As String, strFeilds As String, strRowCount As String
        Try
            strRowCount = strRecordID("tblVisitInvestigations", "count (*)", " VisitId=" & VisitId)
            If Val(strRowCount & "") = 0 Then
                strFeilds = " tblVisitInvestigations(TestType,Test,VisitId)"

                strQuery = "'Other Test'" & ",'" & txtInv.Text & "'," & VisitId

                Call InsertintoTable(strFeilds, strQuery)
            Else
                strQuery = "Test='" & txtInv.Text & "'"

                Call UpdateTable("tblVisitInvestigations", strQuery, " VisitId=" & VisitId & " AND TestType = 'Other Test'")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

    Private Sub SaveSummaryRefferals()
        Cursor.Current = Cursors.WaitCursor
        Dim strQuery As String, strFeilds As String
        Try
            Call DeleteFromTable("tblVisitReferrals", "VisitId=" & VisitId)
            strFeilds = "tblVisitReferrals(SpecialistId,VisitId)"
            With lstReferrals
                For intCtr As Integer = 0 To .ItemCount - 1
                    If .GetItemCheckState(intCtr) = CheckState.Checked Then
                        strQuery = .GetItemValue(intCtr) & "," & VisitId

                        Call InsertintoTable(strFeilds, strQuery)
                    End If
                Next intCtr
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        Finally
            Cursor.Current = Cursors.Default
        End Try
    End Sub

#End Region

#Region "Management Page"
    Private Sub PopulateMgmtCheckLists()

        'Populate LabTest checkList box
        PopulateList(lstlabTests, "SELECT LabTestId,LabTest  FROM LtblLabTests ORDER BY LabTest", "LabTest", "LabTestId")

        'Populate Imaging checkList box
        PopulateList(lstImages, "SELECT ImageTypeId,ImageType  FROM LtblImageType ORDER BY ImageType", "ImageType", "ImageTypeId")

        'Populate Specialist checkList box
        PopulateList(lstSpecialists, "SELECT DoctorId,(Firstname + ' ' + Lastname) as Name FROM tblSpecialists ORDER BY Name", "Name", "DoctorId")
    End Sub

    Private Sub SaveMagmtTab()
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            'save prescription result
            SavePrescription()

            'save investigation data such as lab test and imaging
            SaveInvestigations()

            'save refferals for a patient in tblVisitRefferal
            SaveRefferals()

            'save result such as therapy and whether hospitalised in tblVisitResult
            SaveResult()

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try


    End Sub

    Private Sub SavePrescription()
        Dim strQuery As String

        Call DeleteFromTable("tblVisitPrescription", "VisitId=" & VisitId)

        For intCtr As Integer = 0 To gdvPrescription.RowCount - 1
            If Val(Trim(gdvPrescription.GetRowCellValue(intCtr, "Drug") & "")) <= 0 Then Continue For
            strQuery = Val(gdvPrescription.GetRowCellValue(intCtr, "Drug")) & _
                        "," & Val(gdvPrescription.GetRowCellValue(intCtr, "Drug Dose")) & _
                        "," & Val(gdvPrescription.GetRowCellValue(intCtr, "Drug Dose Unit"))
            If Val(Trim(gdvPrescription.GetRowCellValue(intCtr, "Frequency") & "")) <= 0 Then
                strQuery = strQuery & ",Null"
            Else
                strQuery = strQuery & "," & Val(gdvPrescription.GetRowCellValue(intCtr, "Frequency"))
            End If
            strQuery = strQuery & ",'" & Trim(gdvPrescription.GetRowCellValue(intCtr, "Comments") & "") & "'" & _
                        "," & VisitId
            Call InsertintoTable("tblVisitPrescription", strQuery)
        Next

    End Sub

    Private Sub SaveInvestigations()
        'Delete all the rows for that visit
        Call DeleteFromTable("tblVisitInvestigations", "VisitId=" & VisitId & " and TestType='Lab Test'")

        Dim i As Integer 'loop variable
        Dim strQuery As String
        'get values from list box of lab tests and store them in datatable row
        For i = 0 To lstlabTests.ItemCount - 1
            If lstlabTests.GetItemChecked(i) = True Then
                strQuery = "'Lab Test'" & _
                         ",'" & lstlabTests.GetItemText(i) & "'" & _
                         "," & VisitId
                Call InsertintoTable("tblVisitInvestigations", strQuery)
            End If
        Next

        'get values from list box of Imaging and store them in datatable row
        For i = 0 To lstImages.ItemCount - 1
            If lstImages.GetItemChecked(i) = True Then
                strQuery = "'Imaging'" & _
                            ",'" & lstImages.GetItemText(i) & "'" & _
                            "," & VisitId
                Call InsertintoTable("tblVisitInvestigations", strQuery)
            End If
        Next

        'get data from other tests (txtOther)
        If txtOtherTest.Text <> "" Then
            strQuery = "'Other Test'" & _
                        "," & Trim(SmartReplace(txtOtherTest.Text) & "") & "" & _
                        "," & VisitId
            Call InsertintoTable("tblVisitInvestigations", strQuery)
        End If

    End Sub

    Private Sub SaveRefferals()

        'Delete all the rows for that visit
        Call DeleteFromTable("tblVisitReferrals", "VisitId=" & VisitId)

        Dim i As Integer 'loop variable
        Dim strQuery As String
        'get values from list box of specialists and store them in datatable row
        For i = 0 To lstSpecialists.ItemCount - 1
            If lstSpecialists.GetItemChecked(i) = True Then
                strQuery = lstSpecialists.GetItemValue(i) & _
                            "," & VisitId
                Call InsertintoTable("tblVisitReferrals", strQuery)
            End If
        Next

    End Sub

    Private Sub SaveResult()
        Dim strQuery As String
        Dim Cnt As Integer = Val(strRecordID("tblVisitResult", "VisitResultId", "VisitId=" & VisitId))

        If Cnt > 0 Then
            strQuery = " Therapy=" & Trim(SmartReplace(txtTherapy.Text) & "") & "" & _
                        ", Hospitalised=" & IIf(chkHospitalised.Checked, 1, 0) & ""
            If Not IsDBNullOrNothing(dtSickStartDate.EditValue) Then
                strQuery = strQuery & ",SickStartDate='" & Format(CDate(dtSickStartDate.EditValue), gstrDtFormat) & "'"
            End If
            If Not IsDBNullOrNothing(dtSickEndDate.EditValue) Then
                strQuery = strQuery & ",SickEndDate='" & Format(CDate(dtSickEndDate.EditValue), gstrDtFormat) & "'"
            End If
            If Not IsDBNullOrNothing(txtSickDays.Text) Then
                strQuery = strQuery & ",TotalSickDays=" & Val(txtSickDays.EditValue)
            End If
            If Not IsDBNullOrNothing(cboHospital.EditValue) Then
                strQuery = strQuery & ",HospitalName=" & cboHospital.EditValue & ""
            Else
                strQuery = strQuery & ",HospitalName=Null"
            End If
            Call UpdateTable("tblVisitResult", strQuery, "VisitId=" & VisitId)
        Else
            strQuery = "" & Trim(SmartReplace(txtTherapy.Text) & "") & "" & _
                        "," & IIf(chkHospitalised.Checked, 1, 0) & "" & _
                        "," & VisitId
            If Not IsDBNullOrNothing(dtSickStartDate.EditValue) Then
                strQuery = strQuery & ",'" & Format(CDate(dtSickStartDate.EditValue), gstrDtFormat) & "'"
            Else
                strQuery = strQuery & ",Null"
            End If
            If Not IsDBNullOrNothing(dtSickEndDate.EditValue) Then
                strQuery = strQuery & ",'" & Format(CDate(dtSickEndDate.EditValue), gstrDtFormat) & "'"
            Else
                strQuery = strQuery & ",Null"
            End If
            If Not IsDBNullOrNothing(txtSickDays.Text) Then
                strQuery = strQuery & "," & Val(txtSickDays.EditValue)
            Else
                strQuery = strQuery & ",Null"
            End If
            If Not IsDBNullOrNothing(cboHospital.EditValue) Then
                strQuery = strQuery & "," & Val(cboHospital.EditValue) & ""
            Else
                strQuery = strQuery & ",Null"
            End If
            Call InsertintoTable("tblVisitResult", strQuery)
        End If

    End Sub

    Private Sub PopulatePrescriptionGrid()
        Call SetManagementEditorDataColumn()
        Dim strQuery As String
        Dim dsTemp As DataSet
        strQuery = "SELECT  VisitPrescriptionId as [ID],tblVisitPrescription.DrugId as Drug,DrugDose [Drug Dose], " & _
                    "tblVisitPrescription.DrugDoseUnitId [Drug Dose Unit],Frequency,Comments " & _
                    "FROM tblVisitPrescription WHERE VisitId=" & VisitId
        dsTemp = FillDataSet(strQuery)
        With grdPrescription
            .BeginUpdate()
            .DataSource = dsTemp.Tables(0)
            .EndUpdate()
        End With
        With gdvPrescription
            .Columns("ID").Visible = False
            .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
        End With

    End Sub

    Private Sub InitialiseManagementDataEntry()
        Dim dtTemp As DataTable
        dtTemp = New DataTable("Active")
        With dtTemp.Columns
            .Add("ID", GetType(Integer))
            .Add("Drug", GetType(Integer))
            .Add("Drug Dose", GetType(Decimal))
            .Add("Drug Dose Unit", GetType(Date))
            .Add("Frequency", GetType(Integer))
            .Add("Comments", GetType(String))
        End With
        grdPrescription.DataSource = dtTemp
        gdvPrescription.Columns("ID").Visible = False
        dtTemp.Dispose()
    End Sub

    Private Sub SetManagementEditorDataColumn()
        Try
            Call InitialiseManagementDataEntry()
            'Dim fnBold As New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold)
            With gdvPrescription
                .Columns("ID").Visible = False
                .Columns("ID").OptionsColumn.ShowInCustomizationForm = False
                '.Columns("Drug").AppearanceHeader.Font = fnBold
                .Columns("Drug").Width = 100
                '.Columns("Drug Dose").AppearanceHeader.Font = fnBold
                .Columns("Drug Dose").Width = 100
                '.Columns("Drug Dose Unit").AppearanceHeader.Font = fnBold
                .Columns("Drug Dose Unit").Width = 100
                .OptionsNavigation.EnterMoveNextColumn = True
            End With
            rpglkDrugName = New RepositoryItemGridLookUpEdit()
            Dim DrugNameSize As Size
            DrugNameSize.Width = 250
            DrugNameSize.Height = 40

            Dim dsTemp As DataSet = FillDataSet("select LtblDrugs.DrugId [DrugId], LtblDrugs.DrugName [DrugName] " & _
                                                "from LtblDrugs Join tblDrugs ON LtblDrugs.DrugId=tblDrugs.DrugId " & _
                                                "where tblDrugs.DrugDeleted=0 order by [DrugName]")
            With rpglkDrugName
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp.Tables(0)
                .DisplayMember = "DrugName"
                .ValueMember = "DrugId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DrugId").Visible = False
                .PopupFormMinSize = DrugNameSize
            End With
            dsTemp.Dispose()

            rpglkDrugUnit = New RepositoryItemGridLookUpEdit()
            Dim DrugUnitSize As Size
            DrugUnitSize.Width = 250
            DrugUnitSize.Height = 40
            Dim dsTemp1 As DataSet = FillDataSet("select DrugDoseUnitId,DrugDoseUnit from LtblDrugDoseUnits order by DrugDoseUnit")
            With rpglkDrugUnit
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp1.Tables(0)
                .DisplayMember = "DrugDoseUnit"
                .ValueMember = "DrugDoseUnitId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("DrugDoseUnitId").Visible = False
                .PopupFormMinSize = DrugUnitSize

            End With
            dsTemp1.Dispose()

            rptxtDrugDose = New RepositoryItemTextEdit
            With rptxtDrugDose
                .Mask.MaskType = Mask.MaskType.Numeric
                .Mask.EditMask = "n2"
                .EditFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                .DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric
                .Mask.UseMaskAsDisplayFormat = True
            End With

            rptxtDrugfrequency = New RepositoryItemGridLookUpEdit
            rptxtDrugfrequency.MaxLength = 50
            Dim dsTemp2 As DataSet = FillDataSet("Select FrequencyId, Frequency from LtblFrequency")
            With rptxtDrugfrequency
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp2.Tables(0)
                .DisplayMember = "Frequency"
                .ValueMember = "FrequencyId"
                .NullText = ""
                .ImmediatePopup = True
                .ShowFooter = False
                .View.FocusRectStyle = DrawFocusRectStyle.RowFocus
                .View.OptionsSelection.EnableAppearanceFocusedCell = False
                .View.OptionsView.AutoCalcPreviewLineCount = True
                .View.OptionsFilter.AllowColumnMRUFilterList = True
                .View.OptionsFilter.AllowFilterEditor = True
                .View.OptionsFilter.AllowMRUFilterList = True
                .View.OptionsView.ShowAutoFilterRow = True
                .View.OptionsView.ShowIndicator = False
                .View.OptionsView.ShowGroupPanel = False
                .View.OptionsView.ShowPreview = True
                .View.OptionsFilter.ShowAllTableValuesInFilterPopup = True
                .TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard
                .ImmediatePopup = True
                .ShowFooter = False
                .View.Columns("FrequencyId").Visible = False
                .View.Columns("FrequencyId").Visible = False
            End With

            rptxtDrugComment = New RepositoryItemMemoEdit
            rptxtDrugComment.MaxLength = 50

            grdPrescription.RepositoryItems.AddRange(New DevExpress.XtraEditors.Repository.RepositoryItem() {rpglkDrugName, rpglkDrugUnit, rptxtDrugComment, rptxtDrugDose, rptxtDrugfrequency})
            With gdvPrescription
                .Columns("Drug").ColumnEdit = rpglkDrugName
                .Columns("Drug Dose").ColumnEdit = rptxtDrugDose
                .Columns("Drug Dose Unit").ColumnEdit = rpglkDrugUnit
                .Columns("Frequency").ColumnEdit = rptxtDrugfrequency
                .Columns("Comments").ColumnEdit = rptxtDrugComment
                ' .Columns("Diagnosis").SummaryItem.SetSummary(DevExpress.Data.SummaryItemType.Count, "Total {0} records")
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

#End Region

#Region "Neurology Page"


    Private Sub Calculate_GCS_Total(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbGcsBestMotorResponse.SelectedIndexChanged, cmbGcsBestVerablResponse.SelectedIndexChanged, cmbGcsEyeOpening.SelectedIndexChanged

        'If cmbGcsBestMotorResponse.SelectedIndex = -1 OrElse cmbGcsBestVerablResponse.SelectedIndex = -1 OrElse cmbGcsEyeOpening.SelectedIndex = -1 Then
        '    Exit Sub
        'End If


        'calculate GCS total and assign result to txtGcsTotalScore
        txtGcsTotalScore.Text = cmbGcsBestMotorResponse.SelectedIndex + cmbGcsBestVerablResponse.SelectedIndex + cmbGcsEyeOpening.SelectedIndex + 3
    End Sub

    Private Sub SaveNeurology()

        Dim strQuery As String
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True
            Dim Cnt As Integer = Val(strRecordID("tblVisitNeurology", "VisitNeurologyId", "VisitId=" & VisitId))
            If Cnt > 0 Then
                strQuery = " CranialNerve1=" & Trim(SmartReplace(txtCranialNerveI.Text) & "") & "" & _
                              ", CranialNerve2=" & Trim(SmartReplace(txtCranialNerveII.Text) & "") & "" & _
                              ", CranialNerve346=" & Trim(SmartReplace(txtCranialNerveIII.Text) & "") & "" & _
                              ", CranialNerve7=" & Trim(SmartReplace(txtCranialNerveVII.Text) & "") & "" & _
                              ", CranialNerve8=" & Trim(SmartReplace(txtCranialNerveVIII.Text) & "") & "" & _
                              ", CranialNerve9=" & Trim(SmartReplace(txtCranialNerveIX.Text) & "") & "" & _
                              ", CranialNerve10=" & Trim(SmartReplace(txtCranialNerveX.Text) & "") & "" & _
                              ", CranialNerve11=" & Trim(SmartReplace(txtCranialNerveXI.Text) & "") & "" & _
                              ", CranialNerve12=" & Trim(SmartReplace(txtCranialNerveXII.Text) & "") & "" & _
                              ", SensoryTouch=" & Trim(SmartReplace(txtSensoryTouch.Text) & "") & "" & _
                              ", SensoryTemperature=" & Trim(SmartReplace(txtSensoryTemperature.Text) & "") & "" & _
                              ", SensoryPosition=" & Trim(SmartReplace(txtSensoryPosition.Text) & "") & "" & _
                              ", SensoryVibration=" & Trim(SmartReplace(txtSensoryVibration.Text) & "") & "" & _
                              ", CerebellumFingerToNose=" & Trim(SmartReplace(txtCerebellumFingerToNose.Text) & "") & "" & _
                              ", CerebellumRapidlyRepeated=" & Trim(SmartReplace(txtCerebellumRapidlyRepeated.Text) & "") & "" & _
                              ", CerebellumHeelToChin=" & Trim(SmartReplace(txtCerebellumHeelToChin.Text) & "") & "" & _
                              ", CerebellumTandemWalking=" & Trim(SmartReplace(txtCerebellumTandemWalking.Text) & "") & "" & _
                              ", ReflexRightB=" & Trim(SmartReplace(cmbReflexRightB.SelectedItem) & "") & "" & _
                              ", ReflexRightT=" & Trim(SmartReplace(cmbReflexRightT.SelectedItem) & "") & "" & _
                              ", ReflexRightABDup=" & Trim(SmartReplace(cmbReflexRightABDup.SelectedItem) & "") & "" & _
                              ", ReflexRightABDlow=" & Trim(SmartReplace(cmbReflexRightABDlow.SelectedItem) & "") & "" & _
                              ", ReflexRightK=" & Trim(SmartReplace(cmbReflexRightK.SelectedItem) & "") & "" & _
                              ", ReflexRightA=" & Trim(SmartReplace(cmbReflexRightA.SelectedItem) & "") & "" & _
                              ", ReflexRightP=" & Trim(SmartReplace(cmbReflexRightP.SelectedItem) & "") & "" & _
                              ", ReflexLeftB=" & Trim(SmartReplace(cmbReflexLeftB.SelectedItem) & "") & "" & _
                              ", ReflexLeftT=" & Trim(SmartReplace(cmbReflexLeftT.SelectedItem) & "") & "" & _
                              ", ReflexLeftABDup=" & Trim(SmartReplace(cmbReflexLeftABDup.SelectedItem) & "") & "" & _
                              ", ReflexLeftABDlow=" & Trim(SmartReplace(cmbReflexLeftABDlow.SelectedItem) & "") & "" & _
                              ", ReflexLeftK=" & Trim(SmartReplace(cmbReflexLeftK.SelectedItem) & "") & "" & _
                              ", ReflexLeftA=" & Trim(SmartReplace(cmbReflexLeftA.SelectedItem) & "") & "" & _
                              ", ReflexLeftP=" & Trim(SmartReplace(cmbReflexLeftP.SelectedItem) & "") & "" & _
                              ", Other=" & Trim(SmartReplace(txtOther.Text) & "") & "" & _
                              ", GCSEyeOpening=" & Trim(SmartReplace(cmbGcsEyeOpening.SelectedItem) & "") & "" & _
                              ", GCSBestVerbalResponse=" & Trim(SmartReplace(cmbGcsBestVerablResponse.SelectedItem) & "") & "" & _
                              ", GCSBestMotorResponse=" & Trim(SmartReplace(cmbGcsBestMotorResponse.SelectedItem) & "") & ""

                Call UpdateTable("tblVisitNeurology", strQuery, "VisitId=" & VisitId)

            Else
                strQuery = VisitId & _
                              "," & Trim(SmartReplace(txtCranialNerveI.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveII.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveIII.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveVII.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveVIII.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveIX.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveX.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveXI.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCranialNerveXII.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtSensoryTouch.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtSensoryTemperature.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtSensoryPosition.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtSensoryVibration.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCerebellumFingerToNose.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCerebellumRapidlyRepeated.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCerebellumHeelToChin.Text) & "") & "" & _
                              "," & Trim(SmartReplace(txtCerebellumTandemWalking.Text) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightB.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightT.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightABDup.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightABDlow.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightK.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightA.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexRightP.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftB.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftT.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftABDup.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftABDlow.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftK.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftA.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbReflexLeftP.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(txtOther.Text) & "") & "" & _
                              "," & Trim(SmartReplace(cmbGcsEyeOpening.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbGcsBestVerablResponse.SelectedItem) & "") & "" & _
                              "," & Trim(SmartReplace(cmbGcsBestMotorResponse.SelectedItem) & "") & "" & _
                              ",Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null " & _
                              ",Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null,Null " & _
                              ",Null,Null,Null,Null,Null,Null,Null,Null,Null,Null"
                Call InsertintoTable("tblVisitNeurology", strQuery)

            End If

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub


#End Region

#Region "Default Values"
    'Varibles which stores default values for fields in Tab.
    'For Present History Tab
    'Private DEF_PresentComp As String
    'Private DEF_HistoryPresentComp As String

    'For General Assessmant Tab
    Private DEF_Hydration As String = "Normal"
    Private DEF_Oedema As String = "Nil"
    Private DEF_Nurtition As String = "Normal"
    Private DEF_MucusMembrane1 As String = "Pink"
    Private DEF_MucusMembrane2 As String = "Moist"
    Private DEF_MucusMembrane3 As String = "Acyanotic"
    Private DEF_MucusMembrane4 As String = "Unicteric"
    Private DEF_HandsNArms As String = "NAD"
    Private DEF_Nodes As String = "NAD"
    Private DEF_Skin As String = "NAD"
    Private DEF_BreastCondition As String = "NAD"

    'For Cardiovascular Tab
    Private DEF_Rhythm As String = "Regular"
    Private DEF_Volume As String = "Normal"
    Private DEF_Wave As String = "NAD"
    Private DEF_Arterial As String = "NAD"
    Private DEF_Venous As String = "NAD"
    Private DEF_InspectionHeart As String = "NAD"
    Private DEF_ABPosition As String = "5th LICS MCL"
    Private DEF_ABCharacter As String = "Normal"
    Private DEF_Thrill As String = "Nil"
    Private DEF_S1 As String = "NAD"
    Private DEF_S2 As String = "NAD"
    Private DEF_AddedSound As String = "Nil"
    Private DEF_Murmurs As String = "Nil"

    'For Respiratory Tab
    Private DEF_Cough As String = "Nil"
    Private DEF_Sputum As String = "NAD"
    Private DEF_RespiratoryEffort As String = "NAD"
    Private DEF_Nose As String = "NAD"
    Private DEF_Tonsils As String = "NAD"
    Private DEF_Sinuses As String = "NAD"
    Private DEF_Pharynx As String = "NAD"
    Private DEF_Trachea As String = "NAD"
    Private DEF_InspectionResp As String = "NAD"
    Private DEF_Palpation As String = "NAD"
    Private DEF_Percussion As String = "NAD"
    Private DEF_Auscultation As String = "NAD"

    'For GastroIntestinal Tab
    Private DEF_Mouth As String = "NAD"
    Private DEF_InspectionGI As String = "NAD"
    Private DEF_PalpationGI As String = "NAD"
    Private DEF_PercussionGI As String = "NAD"
    Private DEF_AuscultationGI As String = "NAD"
    Private DEF_Rectum As String = "NAD"
    Private DEF_Anus As String = "NAD"

    'For Genitourinary Tab
    Private DEF_InspectionGU As String = "NAD"
    Private DEF_PalpationGU As String = "NAD"
    Private DEF_Color As String = "Straw"
    Private DEF_Protein As String = "Nil"
    Private DEF_Sugar As String = "Nil"
    Private DEF_Ketone As String = "Nil"
    Private DEF_Blood As String = "Nil"

    'For Locomotion Tab
    Private DEF_Spine As String = "NAD"
    Private DEF_Joints As String = "NAD"
    Private DEF_Muscles As String = "NAD"
    Private DEF_Bones As String = "NAD"
    Private DEF_Gait As String = "NAD"

    'For Neurology Tab
    Private DEF_CranialNerve As String = "NAD"  'Default Values for the Cranial Nerve I,II,III... are same, hence stored in single variable DEF_CranialNerve.
    Private DEF_Reflexes As String = "++"       'Default values of reflexes Left/Right B,T,ABD... (Except P)are same, hence stored in single variable DEF_Reflexes.
    Private DEF_ReflexesP As String = "Down"    'The values of reflexes 'P' both Left and Right are same and is stored in single variable DEF_ReflexesP.
    Private DEF_FingureToNose As String = "NAD"
    Private DEF_RapidlyRepeated As String = "NAD"
    Private DEF_HeelToChin As String = "NAD"
    Private DEF_TendemWalking As String = "NAD"
    Private DEF_Touch As String = "NAD"
    Private DEF_Temperature As String = "NAD"
    Private DEF_Position As String = "NAD"
    Private DEF_Vibration As String = "NAD"
    Private DEF_EyeOpening As String = "Spontaneous (4)"
    Private DEF_BMResponce As String = "Obeys Commands (6)"
    Private DEF_BVResponce As String = "Oriented (5)"

    'For Mental Tab
    Private DEF_GeneralAppearance As String = "NAD"
    Private DEF_ThoughtProcess As String = "NAD"
    Private DEF_Mood As String = "NAD"
    Private DEF_Delusion As String = "Nil"
    Private DEF_Hallucinations As String = "Nil"
    Private DEF_Obsessions As String = "Nil"
    Private DEF_Orientation As String = "NAD"
    Private DEF_Memory As String = "NAD"
    Private DEF_AttentionConcentration As String = "NAD"
    Private DEF_GeneralInformation As String = "NAD"
    Private DEF_Intelligence As String = "NAD"
    Private DEF_InsightJudgement As String = "NAD"
    Private DEF_Speech As String = "NAD"

    Private Sub btnGeneralDefaultValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGeneralDefaultValues.Click
        'Populate Default values in General Assessment Tab.
        cmbHydration.SelectedItem = DEF_Hydration
        cmbOedema.SelectedItem = DEF_Oedema
        cmbNutrition.SelectedItem = DEF_Nurtition
        cmbMucus1.SelectedItem = DEF_MucusMembrane1
        cmbMucus2.SelectedItem = DEF_MucusMembrane2
        cmbMucus3.SelectedItem = DEF_MucusMembrane3
        cmbMucus4.SelectedItem = DEF_MucusMembrane4
        txtHandsArms.Text = DEF_HandsNArms
        txtNodes.Text = DEF_Nodes
        txtSkin.Text = DEF_Skin
        txtBreastCondition.Text = DEF_BreastCondition
    End Sub


    Private Sub btnCardioDefaultValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCardioDefaultValues.Click
        'Populate Default values in CardioVascular Tab.
        txtRhythm.Text = DEF_Rhythm
        txtVolume.Text = DEF_Volume
        txtJVPWave.Text = DEF_Wave
        txtArterial.Text = DEF_Arterial
        txtVenous.Text = DEF_Venous
        txtHeartInspection.Text = DEF_InspectionHeart
        txtApexPosition.Text = DEF_ABPosition
        txtApexCharacter.Text = DEF_ABCharacter
        txtThrill.Text = DEF_Thrill
        txtS1.Text = DEF_S1
        txtS2.Text = DEF_S2
        txtAddedSound.Text = DEF_AddedSound
        txtMurmurs.Text = DEF_Murmurs
    End Sub


    Private Sub btnRespDefaultValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRespDefaultValues.Click
        'Populate Default values in Respiratory Tab.
        txtCough.Text = DEF_Cough
        txtSputum.Text = DEF_Sputum
        txtRepiratoryEffort.Text = DEF_RespiratoryEffort
        txtNose.Text = DEF_Nose
        txtTonsils.Text = DEF_Tonsils
        txtSinuses.Text = DEF_Sinuses
        txtPharnyx.Text = DEF_Pharynx
        txtTrachea.Text = DEF_Trachea
        txtChestInspection.Text = DEF_InspectionResp
        txtChestPalpitation.Text = DEF_Palpation
        txtChestPercussion.Text = DEF_Percussion
        txtChestAuscultation.Text = DEF_Auscultation
    End Sub

    Private Sub btnGastroIntestinalDefaultValue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGastroIntestinalDefaultValue.Click
        'Populate Default values in GastroIntestinal Tab.
        txtMouth.Text = DEF_Mouth
        txtAbodmenInspection.Text = DEF_InspectionGI
        txtAbdomenPalpitation.Text = DEF_PalpationGI
        txtAbdomenPercussion.Text = DEF_PercussionGI
        txtAbdomenAuscultation.Text = DEF_AuscultationGI
        txtRectum.Text = DEF_Rectum
        txtAnus.Text = DEF_Anus
    End Sub

    Private Sub btnGenitoUrineDefaultValue_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenitoUrineDefaultValue.Click
        'Populate Default values in Genitourinary Tab.
        txtGenitaliaInspection.Text = DEF_InspectionGU
        txtGenitaliaPalpitation.Text = DEF_PalpationGU

        'populate sub form urine test
        UrineTestForm.cboColor.SelectedItem = DEF_Color
        UrineTestForm.cboProtein.SelectedItem = DEF_Protein
        UrineTestForm.cboSugar.SelectedItem = DEF_Sugar
        UrineTestForm.cboketone.SelectedItem = DEF_Ketone
        UrineTestForm.cboBlood.SelectedItem = DEF_Blood
    End Sub

    Private Sub btnNeurologyDefaultValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNeurologyDefaultValues.Click
        'Populate Default values in Neurology Tab.

        'NOTE : Default Values for the Cranial Nerve I,II,III... are same, hence stored in single variable DEF_CranialNerve.
        '       Similarly default values of reflexes Left/Right B,T,ABD... (Except P)are same, hence stored in single variable DEF_Reflexes.
        '       And Default values of reflexes 'P' both Left and Right are same, hence stored in single variable DEF_ReflexesP.

        'Populate default values for Cranial Nerve.
        txtCranialNerveI.Text = DEF_CranialNerve
        txtCranialNerveII.Text = DEF_CranialNerve
        txtCranialNerveIII.Text = DEF_CranialNerve
        txtCranialNerveVII.Text = DEF_CranialNerve
        txtCranialNerveVIII.Text = DEF_CranialNerve
        txtCranialNerveIX.Text = DEF_CranialNerve
        txtCranialNerveX.Text = DEF_CranialNerve
        txtCranialNerveXI.Text = DEF_CranialNerve
        txtCranialNerveXII.Text = DEF_CranialNerve

        'Populate default values for Reflexes.
        cmbReflexRightB.SelectedItem = DEF_Reflexes
        cmbReflexLeftB.SelectedItem = DEF_Reflexes
        cmbReflexRightT.SelectedItem = DEF_Reflexes
        cmbReflexLeftT.SelectedItem = DEF_Reflexes
        cmbReflexRightABDup.SelectedItem = DEF_Reflexes
        cmbReflexLeftABDup.SelectedItem = DEF_Reflexes
        cmbReflexRightK.SelectedItem = DEF_Reflexes
        cmbReflexLeftK.SelectedItem = DEF_Reflexes
        cmbReflexLeftABDlow.SelectedItem = DEF_Reflexes
        cmbReflexRightABDlow.SelectedItem = DEF_Reflexes
        cmbReflexRightA.SelectedItem = DEF_Reflexes
        cmbReflexLeftA.SelectedItem = DEF_Reflexes

        cmbReflexRightP.SelectedItem = DEF_ReflexesP
        cmbReflexLeftP.SelectedItem = DEF_ReflexesP

        txtCerebellumFingerToNose.Text = DEF_FingureToNose
        txtCerebellumRapidlyRepeated.Text = DEF_RapidlyRepeated
        txtCerebellumHeelToChin.Text = DEF_HeelToChin
        txtCerebellumTandemWalking.Text = DEF_TendemWalking

        txtSensoryTouch.Text = DEF_Touch
        txtSensoryTemperature.Text = DEF_Temperature
        txtSensoryPosition.Text = DEF_Position
        txtSensoryVibration.Text = DEF_Vibration

        cmbGcsEyeOpening.SelectedItem = DEF_EyeOpening
        cmbGcsBestVerablResponse.SelectedItem = DEF_BVResponce
        cmbGcsBestMotorResponse.SelectedItem = DEF_BMResponce
    End Sub

    Private Sub btnLocomotionDefaultValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLocomotionDefaultValues.Click
        'Populate Default values in Locomotion Tab.
        txtSpine.Text = DEF_Spine
        txtJoints.Text = DEF_Joints
        txtMuscles.Text = DEF_Muscles
        txtBones.Text = DEF_Bones
        txtGait.Text = DEF_Gait
    End Sub

    Private Sub btnMentalDefaultValues_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMentalDefaultValues.Click
        'Populate Default values in Mental Tab.
        txtGeneralAppearance.Text = DEF_GeneralAppearance
        txtThoughtProcess.Text = DEF_ThoughtProcess
        txtMood.Text = DEF_Mood
        txtDelusion.Text = DEF_Delusion
        txtHallucinations.Text = DEF_Hallucinations
        txtObsessions.Text = DEF_Obsessions
        txtOrientation.Text = DEF_Orientation
        txtMemory.Text = DEF_Memory
        txtAttentionConcentration.Text = DEF_AttentionConcentration
        txtGeneralInformation.Text = DEF_GeneralInformation
        txtIntelligence.Text = DEF_Intelligence
        txtInsightJudgement.Text = DEF_InsightJudgement
        txtSpeech.Text = DEF_Speech
    End Sub
#End Region

    Private Sub frmDoctorsNote_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        If mblnActivate = True Then
            mblnActivate = False
            Call SetActiveEditorDataColumn()
            Call SetInActiveEditorDataColumn()
            Call SetManagementEditorDataColumn()
            Call ChangeStatus(VisitId, PatientStatus.WithDoctor)
            Call PopulateLookupDX(cboHospital, "Hospital Name", "HospitalId", "LtblHospital", "HospitalId,HospitalName [Hospital Name]", , "HospitalName", , , 250)

            Call fillAllTabs()
            txtPC.Focus()
            mblnChanged = False
        End If

    End Sub

    Private Sub frmDoctorsNote_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Dim intUnload As DialogResult

        If IsCloseForm = False And mstrFrmName <> "PatientInfo" Then
            intUnload = MessageBox.Show("Is Doctor's visit complete?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
            If intUnload = Windows.Forms.DialogResult.No Then
                Call ChangeStatus(VisitId, PatientStatus.WithDoctor)
            Else

                btnMedicalExamComplete.Enabled = True
                Call ChangeStatus(VisitId, PatientStatus.SeenByDoctor)

                Dim ChargeAndPaymentForm As New frmChargeAndPayment(VisitId, PatientId, GetPracticeId(gintUserID))
                ChargeAndPaymentForm.Text = Me.Text
                ChargeAndPaymentForm.mblnFrmOutside = True
                ChargeAndPaymentForm.MdiParent = Me.ParentForm
                ChargeAndPaymentForm.Show()

            End If
            gblnIsRefreshed = True
            TemplateId = 0
        ElseIf mstrFrmName = "PatientInfo" And blnIsSaved = False Then
            If mblnChanged = True Then
                intUnload = MessageBox.Show("Do you want to save the changes made?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.No Then
                    'e.Cancel = True
                    Exit Sub
                End If
            End If
        End If
        If IsRespiratoryTabValid() = False Then
            xtcNotes.SelectedTabPage = tpgRespiratory
            Exit Sub
        End If

        If IsGeneralAssessmentValid() = False Then
            Exit Sub
        End If


        Cursor.Current = Cursors.WaitCursor

        'Save Summary Details
        'If IsThisTabPopulated(0) = True Then
        saveSummaryTab()
        'End If

        'Save present history, if this tab filled.
        'If IsThisTabPopulated(1) = True Then
        SavePresentHistory()
        'End If

        'Save past history, if this tab filled.
        'If IsThisTabPopulated(2) = True Then
        SavePastHistory()
        'End If

        'Save Genaral assessment, if this tab filled.
        'If IsThisTabPopulated(3) = True Then
        SaveGenAssessment()
        'End If

        'Save Cardiovascular data, if this tab filled.
        'If IsThisTabPopulated(4) = True Then
        SaveCardio()
        'End If

        'Save Respiratory data, if this tab filled.
        'If IsThisTabPopulated(5) = True Then
        SaveRespiratory()
        'End If

        'Save GastroIntestinal data, if this tab filled.
        'If IsThisTabPopulated(6) = True Then
        SaveGastroIntestinal()
        'End If

        'Save Genito Urinary, if this tab filled.
        'If IsThisTabPopulated(7) = True Then
        SaveGenitoUrinary()
        'End If

        'Save Mental data, if this tab filled.
        'If IsThisTabPopulated(8) = True Then
        SaveMental()
        'End If

        'Save Management data, if this tab filled.
        'If IsThisTabPopulated(9) = True Then
        SaveNeurology()
        'End If

        'Save Diagnosis data, if this tab filled.
        'If IsThisTabPopulated(10) = True Then
        SaveLocomotion()
        'End If

        'Save Locomotion data, if this tab filled.
        'If IsThisTabPopulated(11) = True Then
        SaveDiagnosis()
        'End If

        'Save Neurology data, if this tab filled.
        'If IsThisTabPopulated(12) = True Then
        SaveMagmtTab()
        'End If


        'Call FillHospitalName()

        Cursor.Current = Cursors.Default
    End Sub

    Private Sub frmDoctorsNote_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'IsThisTabPopulated is a boolean array which is set to true when tab with given index is populated.After which this tab is not allowed to populate again
        ReDim Preserve IsThisTabPopulated(xtcNotes.TabPages.Count - 1) 'set dimension equal to number of tabs

        'code to find patient id
        Dim PatientName, VisitDate As String
        Dim strQuery As String
        Dim dsTemp As DataSet
        PatientName = ""
        VisitDate = ""

        Call SetImageControl(Me)
        Try
            strQuery = "SELECT  tblPatientInfo.PatientId as PatientId,  PatientTitle + ' ' + (IsNull(LastName + ', ' , '') + FirstName + Isnull(' ' + MiddleName, '') ) AS Name, CAST(tblVisits.VisitDate AS VARCHAR) AS VisitDate  FROM  tblPatientInfo INNER JOIN  tblVisits ON tblPatientInfo.PatientId = tblVisits.PatientId  WHERE  tblVisits.VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    PatientId = .Rows(0).Item("PatientId")
                    PatientName = .Rows(0).Item("Name") & ""
                    VisitDate = .Rows(0).Item("VisitDate") & ""
                End With
            End If
            dsTemp.Dispose()
            Me.Text = PatientName & " (" & VisitDate & ")"


            PopulatePastHistoryControls()

            PopulateGenAssessmentCombos()

            Call SetActiveEditorDataColumn()
            Call SetInActiveEditorDataColumn()
            Call SetManagementEditorDataColumn()


            ' Management tab
            PopulateMgmtCheckLists()

            'Summary tab
            PopulateSummaryLookups()

            FillSummaryTab(VisitId) 'this is the first tab visible to user
            IsThisTabPopulated(0) = True    'Summary tab is filled.
            mblnChanged = False
            txtPC.Focus()
            TemplateId = 0
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillNeurologyTab(ByVal VisitId)
        'fill form with info for that visit ,if it exist

        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT CranialNerve1, CranialNerve346, CranialNerve2, " & _
                                                "CranialNerve7, CranialNerve8, CranialNerve9, CranialNerve10, " & _
                                                "CranialNerve11, CranialNerve12, SensoryTouch, SensoryTemperature, " & _
                                                "SensoryPosition, CerebellumFingerToNose, SensoryVibration, " & _
                                                "CerebellumHeelToChin,CerebellumRapidlyRepeated, CerebellumTandemWalking, " & _
                                                "ReflexRightB, ReflexRightT, ReflexRightABDup, ReflexRightK, " & _
                                                "ReflexRightABDlow,  ReflexRightA, ReflexRightP, ReflexLeftB, " & _
                                                "ReflexLeftT, ReflexLeftABDup, ReflexLeftABDlow, ReflexLeftK, " & _
                                                "ReflexLeftA, ReflexLeftP, Other,   GCSEyeOpening, " & _
                                                "GCSBestVerbalResponse, GCSBestMotorResponse, ToneULLeft, " & _
                                                "ToneLLRight, ToneLLLeft, FingerAbdRight, FingerAbdLeft, " & _
                                                "FingerAddRight, FingerAddLeft, WristFlexRight, WristFlexLeft, " & _
                                                "WristExtRight, WristExtLeft, ElbowFlexRight, ElbowFlexLeft, " & _
                                                "ElbowExtRight, ElbowExtLeft, KneeFlexRight,KneeFlexLeft, " & _
                                                "KneeExtRight, KneeExtLeft, ShoulderFlexRight, ShoulderFlexLeft, " & _
                                                "ShoulderExtRight, ShoulderExtLeft,  ShoulderAbdRight FROM " & _
                                                "tblVisitNeurology WHERE tblVisitNeurology.VisitId = " & VisitId)

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtCranialNerveI.Text = .Rows(0).Item("CranialNerve1") & ""
                    txtCranialNerveII.Text = .Rows(0).Item("CranialNerve2") & ""
                    txtCranialNerveIII.Text = .Rows(0).Item("CranialNerve346") & ""
                    txtCranialNerveVII.Text = .Rows(0).Item("CranialNerve7") & ""
                    txtCranialNerveVIII.Text = .Rows(0).Item("CranialNerve8") & ""
                    txtCranialNerveIX.Text = .Rows(0).Item("CranialNerve9") & ""
                    txtCranialNerveX.Text = .Rows(0).Item("CranialNerve10") & ""
                    txtCranialNerveXI.Text = .Rows(0).Item("CranialNerve11") & ""
                    txtCranialNerveXII.Text = .Rows(0).Item("CranialNerve12") & ""

                    txtSensoryTouch.Text = .Rows(0).Item("SensoryTouch") & ""
                    txtSensoryTemperature.Text = .Rows(0).Item("SensoryTemperature") & ""
                    txtSensoryPosition.Text = .Rows(0).Item("SensoryPosition") & ""
                    txtCerebellumFingerToNose.Text = .Rows(0).Item("CerebellumFingerToNose") & ""
                    txtSensoryVibration.Text = .Rows(0).Item("SensoryVibration") & ""
                    txtCerebellumHeelToChin.Text = .Rows(0).Item("CerebellumHeelToChin") & ""
                    txtCerebellumRapidlyRepeated.Text = .Rows(0).Item("CerebellumRapidlyRepeated") & ""
                    txtCerebellumTandemWalking.Text = .Rows(0).Item("CerebellumTandemWalking") & ""

                    cmbReflexRightB.SelectedItem = .Rows(0).Item("ReflexRightB")
                    cmbReflexRightT.SelectedItem = .Rows(0).Item("ReflexRightT")
                    cmbReflexRightABDup.SelectedItem = .Rows(0).Item("ReflexRightABDup")
                    cmbReflexRightK.SelectedItem = .Rows(0).Item("ReflexRightK")
                    cmbReflexRightABDlow.SelectedItem = .Rows(0).Item("ReflexRightABDlow")
                    cmbReflexRightA.SelectedItem = .Rows(0).Item("ReflexRightA")
                    cmbReflexRightP.SelectedItem = .Rows(0).Item("ReflexRightP")
                    cmbReflexLeftB.SelectedItem = .Rows(0).Item("ReflexLeftB")
                    cmbReflexLeftT.SelectedItem = .Rows(0).Item("ReflexLeftT")
                    cmbReflexLeftABDup.SelectedItem = .Rows(0).Item("ReflexLeftABDup")
                    cmbReflexLeftABDlow.SelectedItem = .Rows(0).Item("ReflexLeftABDlow")
                    cmbReflexLeftK.SelectedItem = .Rows(0).Item("ReflexLeftK")
                    cmbReflexLeftA.SelectedItem = .Rows(0).Item("ReflexLeftA")
                    cmbReflexLeftP.SelectedItem = .Rows(0).Item("ReflexLeftP")
                    txtOther.Text = .Rows(0).Item("Other") & ""

                    cmbGcsEyeOpening.SelectedItem = .Rows(0).Item("GCSEyeOpening")
                    cmbGcsBestVerablResponse.SelectedItem = .Rows(0).Item("GCSBestVerbalResponse")
                    cmbGcsBestMotorResponse.SelectedItem = .Rows(0).Item("GCSBestMotorResponse")

                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub FillGenitoUrinaryTab(ByVal VisitId)
        'fill form with info for that visit ,if it exist

        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT GentitaliaInspection, GentitaliaPalpitation FROM tblVisitGenitoUrinary WHERE tblVisitGenitoUrinary.VisitId = " & VisitId)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtGenitaliaInspection.Text = .Rows(0).Item("GentitaliaInspection") & ""
                    txtGenitaliaPalpitation.Text = .Rows(0).Item("GentitaliaPalpitation") & ""
                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub FillMentalTab(ByVal VisitId)
        'fill form with info for that visit ,if it exist
        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT GeneralAppearence, ThoughtProcess, Mood, Hallucinations, Delusion, Obsessions, Orientation, Memory, AttentionConcentration, GeneralInformation, Intelligence, InsightJudgement, Speech FROM tblVisitMental WHERE tblVisitMental.VisitId = " & VisitId)

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtGeneralAppearance.Text = .Rows(0).Item("GeneralAppearence") & ""
                    txtThoughtProcess.Text = .Rows(0).Item("ThoughtProcess") & ""
                    txtMood.Text = .Rows(0).Item("Mood") & ""
                    txtHallucinations.Text = .Rows(0).Item("Hallucinations") & ""
                    txtDelusion.Text = .Rows(0).Item("Delusion") & ""
                    txtObsessions.Text = .Rows(0).Item("Obsessions") & ""
                    txtOrientation.Text = .Rows(0).Item("Orientation") & ""
                    txtMemory.Text = .Rows(0).Item("Memory") & ""
                    txtAttentionConcentration.Text = .Rows(0).Item("AttentionConcentration") & ""
                    txtGeneralInformation.Text = .Rows(0).Item("GeneralInformation") & ""
                    txtIntelligence.Text = .Rows(0).Item("Intelligence") & ""
                    txtInsightJudgement.Text = .Rows(0).Item("InsightJudgement") & ""
                    txtSpeech.Text = .Rows(0).Item("Speech") & ""
                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub FillGastroIntestinalTab(ByVal VisitId As Integer)
        'fill form with info for that visit ,if it exist
        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT  Mouth, AbdomenInspection, AbdomenPalpitation,AbdomenAuscultation, AbdomenPercussion, Rectum, Anus FROM  tblVisitGastroIntestinal WHERE VisitId = " & VisitId)

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtMouth.Text = .Rows(0).Item("Mouth") & ""
                    txtAbodmenInspection.Text = .Rows(0).Item("AbdomenInspection") & ""
                    txtAbdomenPalpitation.Text = .Rows(0).Item("AbdomenPalpitation") & ""
                    txtAbdomenAuscultation.Text = .Rows(0).Item("AbdomenAuscultation") & ""
                    txtAbdomenPercussion.Text = .Rows(0).Item("AbdomenPercussion") & ""
                    txtRectum.Text = .Rows(0).Item("Rectum") & ""
                    txtAnus.Text = .Rows(0).Item("Anus") & ""
                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillRespiratoryTab(ByVal VisitId As Integer)
        'fill form with info for that visit ,if it exist
        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT     RespiratoryRate, ChestAuscultation, ChestPercussion, ChestPalpitation, Trachea, ChestInspection, Pharnyx, Tonsils, Sinuses, Nose, RespiratoryEffort,  Sputum, Cough, Ear FROM  tblVisitRespiratory WHERE VisitId = " & VisitId)

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    If IsDBNullOrNothing(.Rows(0).Item("RespiratoryRate")) Then
                        txtRespiratoryRate.Text = Nothing
                    Else
                        If Val(txtRespiratoryRate.EditValue) <= 0 Then
                            txtRespiratoryRate.Text = Nothing
                        Else
                            txtRespiratoryRate.Text = Val(.Rows(0).Item("RespiratoryRate"))
                        End If
                    End If
                    txtChestAuscultation.Text = .Rows(0).Item("ChestAuscultation") & ""
                    txtChestPercussion.Text = .Rows(0).Item("ChestPercussion") & ""
                    txtChestPalpitation.Text = .Rows(0).Item("ChestPalpitation") & ""
                    txtChestInspection.Text = .Rows(0).Item("ChestInspection") & ""
                    txtTrachea.Text = .Rows(0).Item("Trachea") & ""
                    txtPharnyx.Text = .Rows(0).Item("Pharnyx") & ""
                    txtTonsils.Text = .Rows(0).Item("Tonsils") & ""
                    txtSinuses.Text = .Rows(0).Item("Sinuses") & ""
                    txtNose.Text = .Rows(0).Item("Nose") & ""
                    txtRepiratoryEffort.Text = .Rows(0).Item("RespiratoryEffort") & ""
                    txtSputum.Text = .Rows(0).Item("Sputum") & ""
                    txtCough.Text = .Rows(0).Item("Cough") & ""
                    txtEar.Text = .Rows(0).Item("Ear") & ""
                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillLocomotionTab(ByVal VisitId As Integer)
        'fill form with info for that visit ,if it exist
        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT     Gait, Bones, Muscles, Joints, Spine FROM         tblVisitLocomotion WHERE VisitId = " & VisitId)

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtGait.Text = .Rows(0).Item("Gait") & ""
                    txtBones.Text = .Rows(0).Item("Bones") & ""
                    txtMuscles.Text = .Rows(0).Item("Muscles") & ""
                    txtJoints.Text = .Rows(0).Item("Joints") & ""
                    txtSpine.Text = .Rows(0).Item("Spine") & ""
                End With
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub

    Private Sub FillPresentHistoryTab(ByVal VisitId As Integer)

        'fill form with info for that visit ,if it exist

        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT PresentingComplaint, PresentingComplaintHistory, History FROM tblVisits WHERE VisitId=" & VisitId)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    txtPresentingComplaint.Text = .Rows(0).Item("PresentingComplaint") & ""
                    txtComplaintHistory.Text = .Rows(0).Item("PresentingComplaintHistory") & ""
                End With

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillManagementTab(ByVal VisitId As Integer)

        'fill form with info for that visit ,if it exist
        Try
            'refferals 
            Dim i, j, k As Integer
            Dim dsTemp As DataSet
            dsTemp = FillDataSet("SELECT SpecialistId  as DoctorId FROM tblVisitReferrals WHERE VisitId=" & VisitId)
            'populate VisitReferrals checked list box
            If dsTemp.Tables(0).Rows.Count > 0 Then
                For i = 0 To dsTemp.Tables(0).Rows.Count - 1
                    For j = 0 To lstSpecialists.ItemCount - 1
                        If lstSpecialists.GetItemValue(j) = dsTemp.Tables(0).Rows(i).Item("DoctorId") Then
                            lstSpecialists.SetItemChecked(j, True)
                            Exit For
                        End If
                    Next
                Next
            End If
            dsTemp.Dispose()
            'Visit Results
            dsTemp = FillDataSet("SELECT Therapy, Hospitalised,SickStartDate,SickEndDate,TotalSickDays,HospitalName FROM   tblVisitResult WHERE VisitId=" & VisitId)
            'fill Therapy  text and Hospitalised check box
            If dsTemp.Tables(0).Rows.Count > 0 Then
                txtTherapy.Text = dsTemp.Tables(0).Rows(0).Item("Therapy") & ""
                chkHospitalised.Checked = dsTemp.Tables(0).Rows(0).Item("Hospitalised")
                If Not IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("SickStartDate")) Then
                    dtSickStartDate.EditValue = Format(dsTemp.Tables(0).Rows(0).Item("SickStartDate"), gstrDtFormat)
                Else
                    dtSickStartDate.EditValue = Nothing
                End If
                If Not IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("SickEndDate")) Then
                    dtSickEndDate.EditValue = Format(dsTemp.Tables(0).Rows(0).Item("SickEndDate"), gstrDtFormat)
                Else
                    dtSickEndDate.EditValue = Nothing
                End If
                If Not IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("TotalSickDays")) Then
                    txtSickDays.Text = Val(dsTemp.Tables(0).Rows(0).Item("TotalSickDays"))
                Else
                    txtSickDays.Text = Nothing
                End If
                If Not IsDBNullOrNothing(dsTemp.Tables(0).Rows(0).Item("HospitalName")) Then
                    cboHospital.EditValue = CInt(dsTemp.Tables(0).Rows(0).Item("HospitalName"))
                Else
                    cboHospital.EditValue = Nothing
                End If
            End If
            dsTemp.Dispose()
            'lab tests etc.
            dsTemp = FillDataSet("SELECT TestType, Test FROM tblVisitInvestigations WHERE VisitID =" & VisitId)

            'fill Lab test  checkedListbox,Imaging checkedListbox and Other textbox
            If dsTemp.Tables(0).Rows.Count > 0 Then
                For i = 0 To dsTemp.Tables(0).Rows.Count - 1
                    For j = 0 To lstlabTests.ItemCount - 1
                        If dsTemp.Tables(0).Rows(i).Item("TestType") = "Lab Test" AndAlso dsTemp.Tables(0).Rows(i).Item("Test") = lstlabTests.GetItemText(j) Then
                            lstlabTests.SetItemChecked(j, True)
                            Exit For
                        End If
                    Next
                Next

                For i = 0 To dsTemp.Tables(0).Rows.Count - 1
                    For k = 0 To lstImages.ItemCount - 1
                        If dsTemp.Tables(0).Rows(i).Item("TestType") = "Imaging" AndAlso dsTemp.Tables(0).Rows(i).Item("Test") = lstImages.GetItemText(k) Then
                            lstImages.SetItemChecked(k, True)
                            Exit For
                        End If
                    Next
                Next

                For i = 0 To dsTemp.Tables(0).Rows.Count - 1
                    If dsTemp.Tables(0).Rows(i).Item("TestType") = "Other Test" Then
                        txtOtherTest.Text = dsTemp.Tables(0).Rows(i).Item("Test")
                    End If
                Next
            End If
            dsTemp.Dispose()
            ''Assign datatable to prescription grid
            PopulatePrescriptionGrid()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillCardiologyTab(ByVal VisitId As Integer)
        'fill form with info for that visit ,if it exist

        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT JVPHeight, JVPWave, Arterial, Venous, BPSupineS, " & _
                                                "BPSupineD, BPSittingS, BPSittingD, BPStandingS, BPStandingD," & _
                                                "S1, S2, AddedSound, Murmurs, ApexCharacter, Thrill, ApexPosition, " & _
                                                "HeartInspection, PulseVolume, PulseRhythm, tblVisitCardiology.Pulse as Rate " & _
                                                "FROM tblVisitCardiology FULL OUTER JOIN tblVisitBPPulse ON " & _
                                                "tblVisitCardiology.VisitId = tblVisitBPPulse.VisitId " & _
                                                "WHERE tblVisitBPPulse.VisitId = " & VisitId)

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    If Not IsDBNullOrNothing(.Rows(0).Item("Rate")) Then
                        If Val(.Rows(0).Item("Rate")) <= 0 Then
                            txtPulse.Text = Nothing
                        Else
                            txtPulse.Text = Val(.Rows(0).Item("Rate"))
                        End If
                    Else
                        txtPulse.Text = Nothing
                    End If
                    txtRhythm.Text = .Rows(0).Item("PulseRhythm") & ""
                    txtVolume.Text = .Rows(0).Item("PulseVolume") & ""
                    If Not IsDBNullOrNothing(.Rows(0).Item("BPSittingD")) Then
                        If Val(.Rows(0).Item("BPSittingD")) <= 0 Then
                            txtBPSittingD.Text = Nothing
                        Else
                            txtBPSittingD.Text = Val(.Rows(0).Item("BPSittingD"))
                        End If
                    Else
                        txtBPSittingD.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("BPSittingS")) Then
                        If Val(.Rows(0).Item("BPSittingS")) <= 0 Then
                            txtBPSittingS.Text = Nothing
                        Else
                            txtBPSittingS.Text = Val(.Rows(0).Item("BPSittingS"))
                        End If
                    Else
                        txtBPSittingS.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("BPSupineD")) Then
                        If Val(.Rows(0).Item("BPSupineD")) <= 0 Then
                            txtBPSupineD.Text = Nothing
                        Else
                            txtBPSupineD.Text = Val(.Rows(0).Item("BPSupineD"))
                        End If
                    Else
                        txtBPSupineD.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("BPSupineS")) Then
                        If Val(.Rows(0).Item("BPSupineS")) <= 0 Then
                            txtBPSupineS.Text = Nothing
                        Else
                            txtBPSupineS.Text = Val(.Rows(0).Item("BPSupineS"))
                        End If
                    Else
                        txtBPSupineS.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("BPStandingD")) Then
                        If Val(.Rows(0).Item("BPStandingD")) <= 0 Then
                            txtBPStandingD.Text = Nothing
                        Else
                            txtBPStandingD.Text = Val(.Rows(0).Item("BPStandingD"))
                        End If
                    Else
                        txtBPStandingD.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("BPStandingS")) Then
                        If Val(.Rows(0).Item("BPStandingS")) <= 0 Then
                            txtBPStandingS.Text = Nothing
                        Else
                            txtBPStandingS.Text = Val(.Rows(0).Item("BPStandingS"))
                        End If

                    Else
                        txtBPStandingS.Text = Nothing
                    End If
                    txtJVPHeight.Text = .Rows(0).Item("JVPHeight") & ""
                    txtJVPWave.Text = .Rows(0).Item("JVPWave") & ""
                    txtArterial.Text = .Rows(0).Item("Arterial") & ""
                    txtVenous.Text = .Rows(0).Item("Venous") & ""
                    txtHeartInspection.Text = .Rows(0).Item("HeartInspection") & ""
                    txtApexCharacter.Text = .Rows(0).Item("ApexCharacter") & ""
                    txtApexPosition.Text = .Rows(0).Item("ApexPosition") & ""
                    txtThrill.Text = .Rows(0).Item("Thrill") & ""
                    txtS1.Text = .Rows(0).Item("S1") & ""
                    txtS2.Text = .Rows(0).Item("S2") & ""
                    txtAddedSound.Text = .Rows(0).Item("AddedSound") & ""
                    txtMurmurs.Text = .Rows(0).Item("Murmurs") & ""

                End With
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub
    Private Sub FillSummaryTab(ByVal VisitId As Integer)
        'Display data in form fields.
        Dim dsTemp As DataSet
        Dim strQuery As String
        Try
            strQuery = "SELECT PresentingComplaint, History, Gen, ENT, RS, CVS, Abd, Mu_SK, NS FROM tblVisits LEFT JOIN tblVisitSummary ON tblVisits.VisitId = tblVisitSummary.VisitId WHERE tblVisits.VisitId=" & VisitId
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtPC.EditValue = .Rows(0).Item("PresentingComplaint")
                    txtSummaryHistory.EditValue = .Rows(0).Item("History")
                    txtGen.EditValue = .Rows(0).Item("Gen")
                    txtENT.EditValue = .Rows(0).Item("ENT")
                    txtRS.EditValue = .Rows(0).Item("RS")
                    txtCVS.EditValue = .Rows(0).Item("CVS")
                    txtAbd.EditValue = .Rows(0).Item("Abd")
                    txtMu_SK.EditValue = .Rows(0).Item("Mu_SK")
                    txtNS.EditValue = .Rows(0).Item("NS")

                End If
            End With

            strQuery = " SELECT RespiratoryRate, BPSupineS, BPSupineD, " & _
                     " tblVisitCardiology.Pulse AS Pulse, " & _
                     " Temperature, TemperatureUnits, " & _
                     " BloodSugar,BloodSugarUnit,Urine, tblVisitResult.Therapy as Therapy" & _
                     " FROM (((((tblVisits LEFT OUTER JOIN tblVisitBPPulse " & _
                     " ON tblVisits.VisitId = tblVisitBPPulse.VisitId )" & _
                     " LEFT OUTER JOIN tblVisitRespiratory " & _
                     " ON tblVisits.VisitID = tblVisitRespiratory.VisitID) " & _
                     " LEFT OUTER JOIN tblVisitGeneralAssessment " & _
                     " ON tblVisits.VisitID=tblVisitGeneralAssessment.VisitID)" & _
                     " LEFT OUTER JOIN tblVisitCardiology " & _
                     " ON tblVisits.VisitID = tblVisitCardiology.VisitID) " & _
                     " LEFT OUTER JOIN tblVisitGenitoUrinary " & _
                     " ON tblVisits.VisitID = tblVisitGenitoUrinary.VisitID)" & _
                     " LEFT OUTER JOIN tblVisitResult " & _
                     " ON tblVisits.VisitID = tblVisitResult.VisitID" & _
                     " WHERE tblVisits.VisitId = " & VisitId

            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    txtR.EditValue = IIf(Val(.Rows(0).Item("RespiratoryRate") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("RespiratoryRate") & "")))

                    txtT.EditValue = IIf(Val(.Rows(0).Item("Temperature") & "") = 0, DBNull.Value, Convert.ToInt64(Val(.Rows(0).Item("Temperature") & "")))
                    If IsDBNullOrNothing(.Rows(0).Item("TemperatureUnits")) Then
                        lkTemperatureUnit.ItemIndex = 0
                    Else
                        lkTemperatureUnit.EditValue = CInt(.Rows(0).Item("TemperatureUnits"))
                    End If

                    txtP.EditValue = IIf(Val(.Rows(0).Item("Pulse") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("Pulse") & "")))
                    txtBPS.EditValue = IIf(Val(.Rows(0).Item("BPSupineS") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("BPSupineS") & "")))
                    txtBPD.EditValue = IIf(Val(.Rows(0).Item("BPSupineD") & "") = 0, DBNull.Value, Convert.ToInt32(Val(.Rows(0).Item("BPSupineD") & "")))

                    txtBloodSugar.EditValue = IIf(Val(.Rows(0).Item("BloodSugar") & "") = 0, DBNull.Value, Convert.ToDouble(Val(.Rows(0).Item("BloodSugar") & "")))
                    If IsDBNullOrNothing(.Rows(0).Item("BloodSugarUnit")) Then
                        lkBloodSugar.ItemIndex = 0
                    Else
                        lkBloodSugar.EditValue = CInt(.Rows(0).Item("BloodSugarUnit"))
                    End If
                    If IsDBNullOrNothing(.Rows(0).Item("Urine")) Then
                        txtUrine.Text = Nothing
                    Else
                        txtUrine.Text = .Rows(0).Item("Urine")
                    End If
                    txtTreatment.EditValue = .Rows(0).Item("Therapy") & ""
                End If
            End With

            strQuery = "SELECT SpecialistId  as DoctorId FROM tblVisitReferrals WHERE VisitId=" & VisitId
            dsTemp = FillDataSet(strQuery, "VisitReferrals")
            Dim i As Integer
            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    'populate VisitReferrals checked list box
                    For i = 0 To .Rows.Count - 1
                        With lstReferrals
                            For intCtr As Integer = 0 To .ItemCount - 1
                                If .GetItemValue(intCtr) = dsTemp.Tables("VisitReferrals").Rows(i).Item("DoctorId") Then
                                    .SetItemCheckState(intCtr, CheckState.Checked)
                                End If
                            Next intCtr
                        End With
                    Next


                End If
            End With

            strQuery = "SELECT TestType, Test FROM tblVisitInvestigations WHERE VisitID =" & VisitId
            dsTemp = FillDataSet(strQuery, "VisitInvestigation")

            For i = 0 To dsTemp.Tables("VisitInvestigation").Rows.Count - 1
                If dsTemp.Tables("VisitInvestigation").Rows(i).Item("TestType") = "Other Test" Then
                    txtInv.Text = dsTemp.Tables("VisitInvestigation").Rows(i).Item("Test")
                End If
            Next

            dsTemp.Dispose()

            strQuery = "Select DiagnosisId,DiagnosisSeverityId from tblVisitDiagnosis where VisitId=" & VisitId
            dsTemp = FillDataSet(strQuery)
            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    If IsDBNullOrNothing(.Rows(0).Item("DiagnosisId")) Then
                        lkAssessment.EditValue = Nothing
                    Else
                        lkAssessment.EditValue = CInt(Val(.Rows(0).Item("DiagnosisId")))
                    End If
                    If IsDBNullOrNothing(.Rows(0).Item("DiagnosisSeverityId")) Then
                        lkSeverity.EditValue = Nothing
                    Else
                        lkSeverity.EditValue = CInt(Val(.Rows(0).Item("DiagnosisSeverityId")))
                    End If

                End If
            End With

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillGeneralAssessmentTab(ByVal VisitId As Integer)

        'fill form with info for that visit ,if it exist
        Try
            Dim dsTemp As DataSet = FillDataSet("SELECT GeneralCondition, Nutrition, MucusMebrane1, MucusMebrane2," & _
                                                "MucusMebrane3, MucusMebrane4, Hydration, Oedema, HandsArms," & _
                                                "Nodes, Skin, BreastCondition, Temperature, TemperatureUnits," & _
                                                "Weight, WeightUnitsId, Height, HeightUnitsId,AbdominalGirth," & _
                                                "AbdominalGirthUnitsId, HeadCircumference, HeadCircumferenceUnitsID " & _
                                                "FROM tblVisitGeneralAssessment WHERE VisitId = " & VisitId)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    If Not IsDBNullOrNothing(.Rows(0).Item("HeadCircumference")) Then
                        If Val(.Rows(0).Item("HeadCircumference")) > 0 Then
                            txtHeadCircimference.Text = Val(.Rows(0).Item("HeadCircumference"))
                        Else
                            txtHeadCircimference.Text = Nothing
                        End If
                    Else
                        txtHeadCircimference.Text = Nothing
                    End If

                    If Not IsDBNullOrNothing(.Rows(0).Item("Temperature")) Then
                        If Val(.Rows(0).Item("Temperature")) > 0 Then
                            txtTemperature.Text = Val(.Rows(0).Item("Temperature"))
                        Else
                            txtTemperature.Text = Nothing
                        End If
                    Else
                        txtTemperature.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("AbdominalGirth")) Then
                        If Val(.Rows(0).Item("AbdominalGirth")) > 0 Then
                            txtAbdominalGirth.Text = Val(.Rows(0).Item("AbdominalGirth"))
                        Else
                            txtAbdominalGirth.Text = Nothing
                        End If
                    Else
                        txtAbdominalGirth.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("Weight")) Then
                        If Val(.Rows(0).Item("Weight")) > 0 Then
                            txtWeight.Text = Val(.Rows(0).Item("Weight"))
                        Else
                            txtWeight.Text = Nothing
                        End If
                    Else
                        txtWeight.Text = Nothing
                    End If
                    If Not IsDBNullOrNothing(.Rows(0).Item("Height")) Then
                        If Val(.Rows(0).Item("Height")) > 0 Then
                            txtHeight.Text = Val(.Rows(0).Item("Height"))
                        Else
                            txtHeight.Text = Nothing
                        End If

                    Else
                        txtHeight.Text = Nothing
                    End If
                    txtBreastCondition.Text = .Rows(0).Item("BreastCondition") & ""
                    txtSkin.Text = .Rows(0).Item("Skin") & ""
                    txtNodes.Text = .Rows(0).Item("Nodes") & ""
                    txtHandsArms.Text = .Rows(0).Item("HandsArms") & ""
                    cmbOedema.SelectedItem = .Rows(0).Item("Oedema")
                    cmbHydration.SelectedItem = .Rows(0).Item("Hydration")
                    cmbMucus1.SelectedItem = .Rows(0).Item("MucusMebrane1")
                    cmbMucus2.SelectedItem = .Rows(0).Item("MucusMebrane2")
                    cmbMucus3.SelectedItem = .Rows(0).Item("MucusMebrane3")
                    cmbMucus4.SelectedItem = .Rows(0).Item("MucusMebrane4")
                    cmbNutrition.SelectedItem = .Rows(0).Item("Nutrition")
                    txtGeneralCondition.Text = .Rows(0).Item("GeneralCondition") & ""


                    'showing up selected units.
                    If Not IsDBNull(.Rows(0).Item("HeightUnitsId")) Then
                        cmbHeightUnit.EditValue = CInt(.Rows(0).Item("HeightUnitsId"))
                    End If

                    If Not IsDBNull(.Rows(0).Item("WeightUnitsId")) Then
                        cmbWeightUnit.EditValue = CInt(.Rows(0).Item("WeightUnitsId"))
                    End If

                    If Not IsDBNull(.Rows(0).Item("AbdominalGirthUnitsID")) Then
                        cmbAbdominalGirthUnit.EditValue = CInt(.Rows(0).Item("AbdominalGirthUnitsID"))
                    End If

                    If Not IsDBNull(.Rows(0).Item("HeadCircumferenceUnitsID")) Then
                        cmbHeadCircumferenceUnit.EditValue = CInt(.Rows(0).Item("HeadCircumferenceUnitsID"))
                    End If

                    If Not IsDBNull(.Rows(0).Item("TemperatureUnits")) Then
                        cmbTemperatureUnit.EditValue = CInt(.Rows(0).Item("TemperatureUnits"))
                    End If


                End With
            Else
                txtHeight.Text = Nothing
                txtWeight.Text = Nothing
                txtAbdominalGirth.Text = Nothing
                txtHeadCircimference.Text = Nothing
                txtTemperature.Text = Nothing
                cmbHeightUnit.EditValue = Nothing
                cmbWeightUnit.EditValue = Nothing
                cmbAbdominalGirthUnit.EditValue = Nothing
                cmbHeadCircumferenceUnit.EditValue = Nothing
                cmbTemperatureUnit.EditValue = Nothing
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub FillDiagnosisTab(ByVal VisitId As Integer)
        Call PopulateActiveGrid()
        Call PopulateInactiveGrid()
    End Sub

    Private Sub FillPastHistoryTab(ByVal VisitId As Integer)
        'fill form with info for that visit ,if it exist

        Try
            Dim strQuery As String = "SELECT  tblVisitPastHistory.HistoryTypeId, tblVisitPastHistory.History FROM  tblVisitPastHistory INNER JOIN  tblPatientInfo ON tblVisitPastHistory.PatientId = tblPatientInfo.PatientId INNER JOIN   tblVisits ON tblPatientInfo.PatientId = tblVisits.PatientId  WHERE tblVisits.VisitId = " & VisitId
            Dim dsTemp As DataSet = FillDataSet(strQuery)

            'no data,exit sub

            If dsTemp.Tables(0).Rows.Count > 0 Then
                With dsTemp.Tables(0)
                    For Each txtTextBox As DevExpress.XtraEditors.TextEdit In txtHistory
                        For i As Integer = 0 To .Rows.Count - 1
                            If txtTextBox.Tag = .Rows(i).Item("HistoryTypeId") AndAlso .Rows(i).Item("HistoryTypeId") <> AllergyTextBoxTag Then
                                txtTextBox.Text = Trim(.Rows(i).Item("History") & "")
                                Exit For
                            End If

                            If txtTextBox.Tag = .Rows(i).Item("HistoryTypeId") AndAlso .Rows(i).Item("HistoryTypeId") = AllergyTextBoxTag Then
                                FillMedicineList(.Rows(i).Item("History") & "") 'this History type is Allergic ,so we will populate lstMedicine.
                                Exit For
                            End If
                        Next
                    Next
                End With
            End If


        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try

    End Sub



    Private Sub FillMedicineList(ByVal AllergyHistoryIdString As String)
        If AllergyHistoryIdString Is Nothing OrElse AllergyHistoryIdString = "" Then Exit Sub
        AllergyHistoryIdString = AllergyHistoryIdString.Trim
        Dim AllergyId As String = ""
        For i As Integer = 0 To AllergyHistoryIdString.Length - 1
            AllergyId = AllergyId & AllergyHistoryIdString.Chars(i)
            If i + 1 = AllergyHistoryIdString.Length OrElse AllergyHistoryIdString.Chars(i + 1) = ","c Then
                For j As Integer = 0 To lstMedicine.ItemCount - 1
                    If lstMedicine.GetItemValue(j) = Convert.ToInt16(AllergyId) Then
                        lstMedicine.SetItemChecked(j, True)
                    End If
                Next
                AllergyId = String.Empty
                i = i + 1 'skip comma
            End If
        Next
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        If IsRespiratoryTabValid() = False Then
            xtcNotes.SelectedTabPage = tpgRespiratory
            Exit Sub
        End If

        If IsGeneralAssessmentValid() = False Then
            Exit Sub
        End If


        Cursor.Current = Cursors.WaitCursor

        'Save Summary Details
        'If IsThisTabPopulated(0) = True Then
        saveSummaryTab()
        'End If

        'Save present history, if this tab filled.
        'If IsThisTabPopulated(1) = True Then
        SavePresentHistory()
        'End If

        'Save past history, if this tab filled.
        'If IsThisTabPopulated(2) = True Then
        SavePastHistory()
        'End If

        'Save Genaral assessment, if this tab filled.
        'If IsThisTabPopulated(3) = True Then
        SaveGenAssessment()
        'End If

        'Save Cardiovascular data, if this tab filled.
        'If IsThisTabPopulated(4) = True Then
        SaveCardio()
        'End If

        'Save Respiratory data, if this tab filled.
        'If IsThisTabPopulated(5) = True Then
        SaveRespiratory()
        'End If

        'Save GastroIntestinal data, if this tab filled.
        'If IsThisTabPopulated(6) = True Then
        SaveGastroIntestinal()
        'End If

        'Save Genito Urinary, if this tab filled.
        'If IsThisTabPopulated(7) = True Then
        SaveGenitoUrinary()
        'End If

        'Save Mental data, if this tab filled.
        'If IsThisTabPopulated(8) = True Then
        SaveMental()
        'End If

        'Save Management data, if this tab filled.
        'If IsThisTabPopulated(9) = True Then
        SaveNeurology()
        'End If

        'Save Diagnosis data, if this tab filled.
        'If IsThisTabPopulated(10) = True Then
        SaveLocomotion()
        'End If

        'Save Locomotion data, if this tab filled.
        'If IsThisTabPopulated(11) = True Then
        SaveDiagnosis()
        'End If

        'Save Neurology data, if this tab filled.
        'If IsThisTabPopulated(12) = True Then
        SaveMagmtTab()
        'End If
        'mblnChanged = False

        'Call FillHospitalName()

        Cursor.Current = Cursors.Default
        Me.Close()
    End Sub

    Private Sub fillAllTabs()
        Call FillPastHistoryTab(VisitId)
        Call FillSummaryTab(VisitId)
        Call FillPresentHistoryTab(VisitId)
        Call FillManagementTab(VisitId)
        Dim i As Integer
        If lstSpecialists.CheckedIndices.Count <> 0 Then
            ReDim SpecialistsIndices(lstSpecialists.CheckedIndices.Count)
            For i = 0 To lstSpecialists.CheckedIndices.Count - 1
                SpecialistsIndices(i) = lstSpecialists.CheckedIndices(i)
            Next
        End If

        If lstlabTests.CheckedIndices.Count <> 0 Then
            ReDim LabTestIndices(lstlabTests.CheckedIndices.Count - 1)
            For i = 0 To lstlabTests.CheckedIndices.Count - 1
                LabTestIndices(i) = lstlabTests.CheckedIndices(i)
            Next
        End If

        If lstImages.CheckedIndices.Count <> 0 Then
            ReDim ImagingIndices(lstImages.CheckedIndices.Count - 1)
            For i = 0 To lstImages.CheckedIndices.Count - 1
                ImagingIndices(i) = lstImages.CheckedIndices.Item(i)
            Next
        End If

        If Not SpecialistsIndices Is Nothing Then
            For Each i In SpecialistsIndices
                lstSpecialists.SetItemChecked(i, True)
            Next
        End If
        If Not LabTestIndices Is Nothing Then
            For Each i In LabTestIndices
                lstlabTests.SetItemChecked(i, True)
            Next
        End If

        If Not ImagingIndices Is Nothing Then
            For Each i In ImagingIndices
                lstImages.SetItemChecked(i, True)
            Next
        End If
        Call FillGeneralAssessmentTab(VisitId)
        Call FillLocomotionTab(VisitId)
        Call FillRespiratoryTab(VisitId)
        Call FillGastroIntestinalTab(VisitId)
        Call FillCardiologyTab(VisitId)
        Call FillMentalTab(VisitId)
        Call FillGenitoUrinaryTab(VisitId)
        Call FillNeurologyTab(VisitId)
        Call InitialiseActiveDataEntry()
        Call InitialiseInActiveDataEntry()
        Call FillDiagnosisTab(VisitId)
    End Sub
    Private Sub xtcNotes_SelectedPageChanged(ByVal sender As Object, ByVal e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles xtcNotes.SelectedPageChanged
        If xtcNotes.SelectedTabPage Is tpgGenitoUrinary Then
            UrineTestForm = New frmUrineTest(VisitId, False)
            UrineTestForm.TopLevel = False
            tpgGenitoUrinary.Controls.Add(UrineTestForm)
            With UrineTestForm
                .Location = New Point(xtcNotes.Left + 420, xtcNotes.Top + 30) 'show this form at specific location on form
                .Size = New Size(New Point(UrineTestForm.Width, 296))
                .ControlBox = False
                .btnSave.Visible = False
                .grpFooter.Visible = False
                .FormBorderStyle = FormBorderStyle.None
                .Show()
                .BringToFront()
            End With
        End If

        If xtcNotes.SelectedTabPage Is tpgDiagnosis Then
            Call FillDiagnosisTab(VisitId)
        End If

    End Sub


    Private Function IsRespiratoryTabValid() As Boolean
        If Trim(txtRespiratoryRate.Text) <> String.Empty AndAlso Convert.ToSingle(Trim(txtRespiratoryRate.Text)) <= 0 Then
            MessageBox.Show("Please enter valid Respiratory Rate.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            xtcNotes.SelectedTabPage = tpgRespiratory
            txtRespiratoryRate.Focus()
            txtRespiratoryRate.SelectAll()
            Return False
        End If

        Return True
    End Function

    Private Sub btnPatientInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPatientInfo.Click
        Dim PatientInfoForm As New frmPatientInfo(PatientId)
        PatientInfoForm.ShowDialog()
    End Sub

    Private Sub btnDrugDetail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDrugDetail.Click
        If Val(Trim(gdvPrescription.GetRowCellValue(gdvPrescription.FocusedRowHandle, "Drug") & "")) <= 0 Then
            MessageBox.Show("Please select Drug.", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If
        'Pass cmbMedication.EditValue value to this form from here
        Dim DrugDetailForm As New frmDrugDetails()
        With DrugDetailForm
            .mlngDrugId = Val(gdvPrescription.GetRowCellValue(gdvPrescription.FocusedRowHandle, "Drug"))
            .ShowDialog()
            .btnEdit_Click(Nothing, Nothing)
            .Dispose()
            DrugDetailForm = Nothing
            GC.Collect()
        End With
    End Sub

    Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If IsRespiratoryTabValid() = False Then
            xtcNotes.SelectedTabPage = tpgRespiratory
            Exit Sub
        End If

        If IsGeneralAssessmentValid() = False Then
            Exit Sub
        End If


        Cursor.Current = Cursors.WaitCursor

        'Save Summary Details
        'If IsThisTabPopulated(0) = True Then
        saveSummaryTab()
        'End If




        'Save present history, if this tab filled.
        'If IsThisTabPopulated(1) = True Then
        SavePresentHistory()
        'End If

        'Save past history, if this tab filled.
        'If IsThisTabPopulated(2) = True Then
        SavePastHistory()
        'End If

        'Save Genaral assessment, if this tab filled.
        'If IsThisTabPopulated(3) = True Then
        SaveGenAssessment()
        'End If

        'Save Cardiovascular data, if this tab filled.
        'If IsThisTabPopulated(4) = True Then
        SaveCardio()
        'End If

        'Save Respiratory data, if this tab filled.
        'If IsThisTabPopulated(5) = True Then
        SaveRespiratory()
        'End If

        'Save GastroIntestinal data, if this tab filled.
        'If IsThisTabPopulated(6) = True Then
        SaveGastroIntestinal()
        'End If

        'Save Genito Urinary, if this tab filled.
        'If IsThisTabPopulated(7) = True Then
        SaveGenitoUrinary()
        'End If

        'Save Mental data, if this tab filled.
        'If IsThisTabPopulated(8) = True Then
        SaveMental()
        'End If

        'Save Management data, if this tab filled.
        'If IsThisTabPopulated(9) = True Then
        SaveNeurology()
        'End If

        'Save Diagnosis data, if this tab filled.
        'If IsThisTabPopulated(10) = True Then
        SaveLocomotion()
        'End If

        'Save Locomotion data, if this tab filled.
        'If IsThisTabPopulated(11) = True Then
        SaveDiagnosis()
        'End If

        'Save Neurology data, if this tab filled.
        'If IsThisTabPopulated(12) = True Then
        SaveMagmtTab()
        'End If

        blnIsSaved = True
        Cursor.Current = Cursors.Default
        mblnChanged = False
        'Inform User
        MessageBox.Show("Doctor notes saved.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Question)
        'Close when data is saved.
        ' '' '' ''IsCloseForm = True
        ' '' '' ''Me.Close()
    End Sub

    Private Sub btnMedicalExamComplete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMedicalExamComplete.Click
        If IsRespiratoryTabValid() = False Then
            xtcNotes.SelectedTabPage = tpgRespiratory
            Exit Sub
        End If

        If IsGeneralAssessmentValid() = False Then
            Exit Sub
        End If


        Cursor.Current = Cursors.WaitCursor

        'Save Summary Details
        'If IsThisTabPopulated(0) = True Then
        saveSummaryTab()
        'End If

        'Save present history, if this tab filled.
        'If IsThisTabPopulated(1) = True Then
        SavePresentHistory()
        'End If

        'Save past history, if this tab filled.
        'If IsThisTabPopulated(2) = True Then
        SavePastHistory()
        'End If

        'Save Genaral assessment, if this tab filled.
        'If IsThisTabPopulated(3) = True Then
        SaveGenAssessment()
        'End If

        'Save Cardiovascular data, if this tab filled.
        'If IsThisTabPopulated(4) = True Then
        SaveCardio()
        'End If

        'Save Respiratory data, if this tab filled.
        'If IsThisTabPopulated(5) = True Then
        SaveRespiratory()
        'End If

        'Save GastroIntestinal data, if this tab filled.
        'If IsThisTabPopulated(6) = True Then
        SaveGastroIntestinal()
        'End If

        'Save Genito Urinary, if this tab filled.
        'If IsThisTabPopulated(7) = True Then
        SaveGenitoUrinary()
        'End If

        'Save Mental data, if this tab filled.
        'If IsThisTabPopulated(8) = True Then
        SaveMental()
        'End If

        'Save Management data, if this tab filled.
        'If IsThisTabPopulated(9) = True Then
        SaveNeurology()
        'End If

        'Save Diagnosis data, if this tab filled.
        'If IsThisTabPopulated(10) = True Then
        SaveLocomotion()
        'End If

        'Save Locomotion data, if this tab filled.
        'If IsThisTabPopulated(11) = True Then
        SaveDiagnosis()
        'End If

        'Save Neurology data, if this tab filled.
        'If IsThisTabPopulated(12) = True Then
        SaveMagmtTab()
        'End If


        Cursor.Current = Cursors.Default

        Dim intUnload As DialogResult
        If mstrFrmName <> "PatientInfo" Then
            intUnload = MessageBox.Show("Is Doctor's visit complete?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
            If intUnload = Windows.Forms.DialogResult.No Then
                Call ChangeStatus(VisitId, PatientStatus.WithDoctor)
                IsCloseForm = True
                Me.Close()
                Exit Sub
            Else
                IsCloseForm = True
                Dim Name As String = Me.Text
                If isLoaded("frmChargeAndPayment") Then
                    Me.Close()
                    Exit Sub
                End If
                ChangeStatus(VisitId, PatientStatus.SeenByDoctor)
                Dim ChargeAndPaymentForm As New frmChargeAndPayment(VisitId, PatientId, GetPracticeId(gintUserID))
                ChargeAndPaymentForm.Text = Name
                ChargeAndPaymentForm.mblnFrmOutside = True
                ChargeAndPaymentForm.MdiParent = Me.ParentForm
                Me.Close()
                ChargeAndPaymentForm.Show()

            End If
            gblnIsRefreshed = True
        Else
            ChangeStatus(VisitId, PatientStatus.SeenByDoctor)

            blnOpnCharge = True
            IsCloseForm = True
            Me.Close()
            
        End If



    End Sub

    Private Function isLoaded(ByVal strFormName As String, Optional ByVal strTag As String = "") As Boolean
        isLoaded = False
        For Each frmchild As Form In Me.ParentForm.MdiChildren
            If Not (frmchild.Tag Is Nothing) Then
                If frmchild.Name.ToString = strFormName And frmchild.Tag.ToString = strTag Then
                    isLoaded = True : frmchild.BringToFront() : Exit Function
                End If
            ElseIf frmchild.Tag Is Nothing Or frmchild.Tag = String.Empty Then
                If frmchild.Name.ToString = strFormName And strTag = String.Empty Then
                    isLoaded = True : frmchild.BringToFront() : Exit Function
                End If
            End If
        Next
    End Function

    Private Sub btnReviewSystems_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReviewSystems.Click
        Dim ROSForm As New frmReviewOfSystem(VisitId)
        ROSForm.Location = New Point(Me.Left + 464, Me.Top + 100) 'show this form at specific location on form
        ROSForm.ShowDialog()
    End Sub

    Private Sub brnMotorSystem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles brnMotorSystem.Click
        Dim MotorSystemForm As New frmMotorSystem(VisitId)
        With MotorSystemForm
            .StartPosition = FormStartPosition.CenterScreen
            .MdiParent = Me.ParentForm
            .Show()
        End With
    End Sub


    Private Sub btnDown_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDown.Click
        Dim dtNTemp1 As DataTable = grdInactive.DataSource
        If Val(Trim(gdvActive.GetRowCellValue(gdvActive.FocusedRowHandle, "Diagnosis") & "")) <= 0 Then
            MessageBox.Show("Please Select the Active details first", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            gdvActive.Focus()
            gdvActive.FocusedColumn = gdvActive.VisibleColumns(0)
            gdvActive.ShowEditor()
            Exit Sub
        End If
        Dim drActive As DataRow = gdvActive.GetDataRow(gdvActive.FocusedRowHandle)
        Dim drTemp As DataRow = dtNTemp1.NewRow()
        drTemp("ID") = drActive("ID")
        drTemp("Diagnosis") = drActive("Diagnosis")
        drTemp("DiagnosisSeverity") = drActive("DiagnosisSeverity")
        drTemp("DiagnosisDate") = drActive("DiagnosisDate")
        drTemp("Active") = False
        dtNTemp1.Rows.Add(drTemp)

        grdActive.BeginUpdate()
        grdActive.EmbeddedNavigator.Buttons.DoClick(grdActive.EmbeddedNavigator.Buttons.Remove)
        dtNTemp1.AcceptChanges()
        grdActive.EndUpdate()
    End Sub

    Private Sub btnUp_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUp.Click
        Dim dtNTemp1 As DataTable = grdActive.DataSource
        If Val(Trim(gdvInactive.GetRowCellValue(gdvInactive.FocusedRowHandle, "Diagnosis") & "")) <= 0 Then
            MessageBox.Show("Please Select the InActive details first", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            gdvInactive.Focus()
            gdvInactive.FocusedColumn = gdvInactive.VisibleColumns(0)
            gdvInactive.ShowEditor()
            Exit Sub
        End If
        Dim drInActive As DataRow = gdvInactive.GetDataRow(gdvInactive.FocusedRowHandle)
        Dim drTemp As DataRow = dtNTemp1.NewRow()
        drTemp("ID") = drInActive("ID")
        drTemp("Diagnosis") = drInActive("Diagnosis")
        drTemp("DiagnosisSeverity") = drInActive("DiagnosisSeverity")
        drTemp("DiagnosisDate") = drInActive("DiagnosisDate")
        drTemp("Active") = True
        dtNTemp1.Rows.Add(drTemp)

        grdInactive.BeginUpdate()
        grdInactive.EmbeddedNavigator.Buttons.DoClick(grdInactive.EmbeddedNavigator.Buttons.Remove)
        dtNTemp1.AcceptChanges()
        grdInactive.EndUpdate()
    End Sub

    Private Sub dtSickStartDate_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        If Not IsDBNullOrNothing(dtSickStartDate.EditValue) AndAlso Not IsDBNullOrNothing(dtSickEndDate.EditValue) Then
            If CDate(dtSickStartDate.EditValue) > CDate(dtSickEndDate.EditValue) Then
                MessageBox.Show("Please select proper end date", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                dtSickEndDate.EditValue = Nothing
                txtSickDays.Text = Nothing
                dtSickEndDate.Focus()
                Exit Sub
            End If
            txtSickDays.Text = DateDiff(DateInterval.Day, CDate(dtSickStartDate.EditValue), CDate(dtSickEndDate.EditValue + 1))
        Else
            txtSickDays.Text = Nothing
        End If
    End Sub

    Private Sub dtSickEndDate_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        If Not IsDBNullOrNothing(dtSickStartDate.EditValue) AndAlso Not IsDBNullOrNothing(dtSickEndDate.EditValue) Then
            If CDate(dtSickStartDate.EditValue) > CDate(dtSickEndDate.EditValue) Then
                MessageBox.Show("Please select proper end date", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                dtSickEndDate.Focus()
                dtSickEndDate.EditValue = Nothing
                txtSickDays.Text = Nothing
                Exit Sub
            End If
            txtSickDays.Text = DateDiff(DateInterval.Day, CDate(dtSickStartDate.EditValue), CDate(dtSickEndDate.EditValue + 1))
        Else
            txtSickDays.Text = Nothing
        End If
    End Sub

    Private Sub txtPresentingComplaint_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtPresentingComplaint.KeyDown, txtVolume.KeyDown, txtTrachea.KeyDown, txtTonsils.KeyDown, txtSputum.KeyDown, txtSinuses.KeyDown, txtRhythm.KeyDown, txtRepiratoryEffort.KeyDown, txtPharnyx.KeyDown, txtNose.KeyDown, txtMouth.KeyDown, txtJVPWave.KeyDown, txtHeartInspection.KeyDown, txtGeneralCondition.KeyDown, txtEar.KeyDown, txtCough.KeyDown, txtComplaintHistory.KeyDown, txtChestPercussion.KeyDown, txtChestPalpitation.KeyDown, txtChestInspection.KeyDown, txtChestAuscultation.KeyDown, txtApexPosition.KeyDown, txtApexCharacter.KeyDown, txtThoughtProcess.KeyDown, txtTherapy.KeyDown, txtSpine.KeyDown, txtSpeech.KeyDown, txtRectum.KeyDown, txtOtherTest.KeyDown, txtOther.KeyDown, txtOrientation.KeyDown, txtObsessions.KeyDown, txtMuscles.KeyDown, txtMood.KeyDown, txtMemory.KeyDown, txtJoints.KeyDown, txtIntelligence.KeyDown, txtInsightJudgement.KeyDown, txtHallucinations.KeyDown, txtGenitaliaPalpitation.KeyDown, txtGenitaliaInspection.KeyDown, txtGeneralInformation.KeyDown, txtGeneralAppearance.KeyDown, txtGait.KeyDown, txtDelusion.KeyDown, txtBones.KeyDown, txtAttentionConcentration.KeyDown, txtAnus.KeyDown, txtAbodmenInspection.KeyDown, txtAbdomenPercussion.KeyDown, txtAbdomenPalpitation.KeyDown, txtAbdomenAuscultation.KeyDown, txtSkin.KeyDown, txtNodes.KeyDown, txtHandsArms.KeyDown, txtBreastCondition.KeyDown, txtTreatment.KeyDown, txtSummaryHistory.KeyDown, txtRS.KeyDown, txtPC.KeyDown, txtNS.KeyDown, txtMu_SK.KeyDown, txtInv.KeyDown, txtGen.KeyDown, txtENT.KeyDown, txtCVS.KeyDown, txtAbd.KeyDown
        If e.KeyCode = Keys.Enter Then
            Call NotesFocus(sender)
        End If
    End Sub

    Private Sub txtPC_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPC.TextChanged
        If txtPC.Text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtPresentingComplaint.Text = txtPC.Text
        End If
    End Sub

    Private Sub txtPresentingComplaint_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPresentingComplaint.TextChanged
        If txtPresentingComplaint.Text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgPresentHistory Then
            txtPC.Text = txtPresentingComplaint.Text
        End If
    End Sub

    Private Sub txtSummaryHistory_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSummaryHistory.TextChanged
        If txtSummaryHistory.Text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtPresentingComplaint.Text = txtSummaryHistory.Text
        End If
    End Sub

    Private Sub txtGen_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtGen.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtGeneralCondition.Text = txtGen.Text
        End If
    End Sub

    Private Sub txtGeneralCondition_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtGeneralCondition.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgGeneralAssessment Then
            txtGen.Text = txtGeneralCondition.Text
        End If
    End Sub

    Private Sub txtENT_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtENT.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtCough.Text = txtENT.Text
        End If
    End Sub

    Private Sub txtCough_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtCough.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgRespiratory Then
            txtENT.Text = txtCough.Text
        End If
    End Sub

    Private Sub txtAbd_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtAbd.TextChanged
        If Trim(sender.text) <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtMouth.Text = txtAbd.Text
        End If
    End Sub

    Private Sub txtMouth_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtMouth.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If

        If xtcNotes.SelectedTabPage Is tpgGastroIntestinal Then
            txtAbd.Text = txtMouth.Text
        End If
    End Sub

    Private Sub txtAbdomenAuscultation_Validated(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtAbdomenAuscultation.Validated, txtPresentingComplaint.Validated, txtVolume.Validated, txtTrachea.Validated, txtTonsils.Validated, txtSputum.Validated, txtSpine.Validated, txtSkin.Validated, txtSinuses.Validated, txtRhythm.Validated, txtRepiratoryEffort.Validated, txtRectum.Validated, txtPharnyx.Validated, txtOther.Validated, txtNose.Validated, txtNodes.Validated, txtMuscles.Validated, txtMouth.Validated, txtJVPWave.Validated, txtJoints.Validated, txtHeartInspection.Validated, txtHandsArms.Validated, txtGenitaliaPalpitation.Validated, txtGenitaliaInspection.Validated, txtGeneralCondition.Validated, txtGait.Validated, txtEar.Validated, txtCough.Validated, txtComplaintHistory.Validated, txtChestPercussion.Validated, txtChestPalpitation.Validated, txtChestInspection.Validated, txtChestAuscultation.Validated, txtBreastCondition.Validated, txtBones.Validated, txtApexPosition.Validated, txtApexCharacter.Validated, txtAnus.Validated, txtAbodmenInspection.Validated, txtAbdomenPercussion.Validated, txtAbdomenPalpitation.Validated, txtThoughtProcess.Validated, txtSpeech.Validated, txtOtherTest.Validated, txtOrientation.Validated, txtObsessions.Validated, txtMood.Validated, txtMemory.Validated, txtIntelligence.Validated, txtInsightJudgement.Validated, txtHallucinations.Validated, txtGeneralInformation.Validated, txtGeneralAppearance.Validated, txtDelusion.Validated, txtAttentionConcentration.Validated, txtTreatment.Validated, txtSummaryHistory.Validated, txtRS.Validated, txtPC.Validated, txtNS.Validated, txtMu_SK.Validated, txtInv.Validated, txtGen.Validated, txtENT.Validated, txtCVS.Validated, txtAbd.Validated
        sender.text = TrimX(sender.text)
    End Sub

    Private Sub HLinkPC_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkPC.OpenLink
        xtcNotes.SelectedTabPage = tpgPresentHistory
        If Not IsDBNullOrNothing(txtPC.Text) Then
            txtPresentingComplaint.Text = txtPC.Text
        End If
    End Sub

    Private Sub HLinkGen_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkGen.OpenLink
        xtcNotes.SelectedTabPage = tpgGeneralAssessment
        If Not IsDBNullOrNothing(txtGen.Text) Then
            txtGeneralCondition.Text = txtGen.Text
        End If
    End Sub

    Private Sub HLinkEnt_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkEnt.OpenLink
        xtcNotes.SelectedTabPage = tpgRespiratory
        If Not IsDBNullOrNothing(txtENT.Text) Then
            txtCough.Text = txtENT.Text
        End If
    End Sub

    Private Sub HLinkRS_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkRS.OpenLink
        xtcNotes.SelectedTabPage = tpgRespiratory

    End Sub

    Private Sub HLinkCSV_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkCSV.OpenLink
        xtcNotes.SelectedTabPage = tpgCardiology

    End Sub

    Private Sub HLinkAbd_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkAbd.OpenLink
        xtcNotes.SelectedTabPage = tpgGastroIntestinal
        If Not IsDBNullOrNothing(txtAbd.Text) Then
            txtMouth.Text = txtAbd.Text
        End If
    End Sub

    Private Sub HLinkA_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkA.OpenLink
        xtcNotes.SelectedTabPage = tpgDiagnosis
    End Sub

    Private Sub HLinkP_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkP.OpenLink
        xtcNotes.SelectedTabPage = tpgManagement
    End Sub

    Private Sub HLinkHistory_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkHistory.OpenLink
        xtcNotes.SelectedTabPage = tpgPresentHistory
        If Not IsDBNullOrNothing(txtSummaryHistory.Text) Then
            txtPresentingComplaint.Text = txtSummaryHistory.Text
        End If
    End Sub

    Private Sub HLinkNS_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkNS.OpenLink
        xtcNotes.SelectedTabPage = tpgNeurology
    End Sub

    Private Sub HLinkMu_SK_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkMu_SK.OpenLink
        xtcNotes.SelectedTabPage = tpgLocomotion
    End Sub

    Private Sub HLinkUrine_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkUrine.OpenLink
        xtcNotes.SelectedTabPage = tpgGenitoUrinary
    End Sub

    Private Sub btnDiagnosisAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDiagnosisAdd.Click
        Try
            If lkAssessment.EditValue = 0 Then
                MessageBox.Show("Please select problem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                lkAssessment.Focus()
                Exit Sub
            End If
            If lkAssessment.Enabled = False Then Exit Sub
            Dim AssessmentID As Integer = Val(strRecordID("tblVisitDiagnosis", "DiagnosisId", "VisitId=" & VisitId & " and DiagnosisId=" & lkAssessment.EditValue))
            If AssessmentID > 0 Then
                MessageBox.Show("This Assessment details already exists on this visit.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                lkAssessment.Focus()
                Exit Sub
            End If
            Dim strFeilds As String = "tblVisitDiagnosis(DiagnosisId,Diagnosis,DiagnosisSeverityId,VisitId,DiagnosisDate,Active,ResolveDate)"
            Dim strQuery As String = lkAssessment.EditValue & ",'" & lkAssessment.Text & "'," & IIf(IsDBNullOrNothing(lkSeverity.EditValue) = True, "NULL", lkSeverity.EditValue) & "," & VisitId & " ,'" & DateTime.Today & "',1,NULL"
            'Add selected Diagnosis into database and Disable combos.
            Call InsertintoTable(strFeilds, strQuery)
            Call PopulateActiveGrid()
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub gdvPrescription_InvalidRowException(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) Handles gdvPrescription.InvalidRowException
        e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction
    End Sub

    Private Sub gdvPrescription_ValidateRow(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) Handles gdvPrescription.ValidateRow
        Try
            Dim view As ColumnView = CType(sender, ColumnView)
            Dim colName As New GridColumn
            Dim blnError As Boolean

            If IsDBNullOrNothing(gdvPrescription.GetRowCellValue(gdvPrescription.FocusedRowHandle, "Drug")) AndAlso IsDBNullOrNothing(gdvPrescription.GetRowCellValue(gdvPrescription.FocusedRowHandle, "Drug Dose")) AndAlso IsDBNullOrNothing(gdvPrescription.GetRowCellValue(gdvPrescription.FocusedRowHandle, "Drug Dose Unit")) Then Exit Sub
            If Val(Trim(gdvPrescription.GetRowCellValue(e.RowHandle, "Drug") & "")) <= 0 Then
                colName = view.Columns("Drug") : blnError = True : view.SetColumnError(colName, "Specify Drug")
            ElseIf Val(Trim(gdvPrescription.GetRowCellValue(e.RowHandle, "Drug Dose") & "")) <= 0 Then
                colName = view.Columns("Drug Dose") : blnError = True : view.SetColumnError(colName, "Specify Drug Dose")
            ElseIf Val(Trim(gdvPrescription.GetRowCellValue(e.RowHandle, "Drug Dose Unit") & "")) <= 0 Then
                colName = view.Columns("Drug Dose Unit") : blnError = True : view.SetColumnError(colName, "Specify Drug Dose Unit")
            End If
            If blnError = True Then view.FocusedColumn = colName : e.Valid = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Call SavePrescription()
        Call ShowPrescriptionReport(VisitId, GetPatientId(VisitId), Me.ParentForm)
    End Sub

    Private Function GetPatientId(ByVal VisitId As Integer) As String
        'get patientname ,kyu from patinet Id
        Dim PatientId As Integer
        Dim dsTemp As DataSet
        Dim strQuery As String

        Try
            strQuery = "SELECT tblPatientInfo.PatientId from tblPatientInfo INNER JOIN tblVisits ON tblPatientInfo.PatientId=tblVisits.PatientId WHERE VisitId = " & VisitId
            dsTemp = FillDataSet(strQuery)
            If dsTemp.Tables(0).Rows.Count > 0 Then
                PatientId = dsTemp.Tables(0).Rows(0).Item("PatientId")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
        Return PatientId
    End Function


    Private Sub HLinkRespRate_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkRespRate.OpenLink
        xtcNotes.SelectedTabPage = tpgRespiratory
        If Not IsDBNullOrNothing(txtR.Text) Then
            txtRespiratoryRate.Text = txtR.Text
        End If
    End Sub

    Private Sub HLinkTemperature_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkTemperature.OpenLink
        xtcNotes.SelectedTabPage = tpgGeneralAssessment
        If Not IsDBNullOrNothing(txtT.Text) Then
            txtTemperature.Text = txtT.Text
        End If
        If Not IsDBNullOrNothing(cmbTemperatureUnit.EditValue) Then
            lkTemperatureUnit.EditValue = CInt(cmbTemperatureUnit.EditValue)
        End If
    End Sub

    Private Sub HLinkPulse_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkPulse.OpenLink
        xtcNotes.SelectedTabPage = tpgCardiology
        If Not IsDBNullOrNothing(txtP.Text) Then
            txtPulse.Text = txtP.Text
        End If
    End Sub

    Private Sub HLinkBP_OpenLink(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.OpenLinkEventArgs) Handles HLinkBP.OpenLink
        xtcNotes.SelectedTabPage = tpgCardiology
        If Not IsDBNullOrNothing(txtBPS.Text) Then
            txtBPSupineS.Text = txtBPS.Text
        End If
        If Not IsDBNullOrNothing(txtBPD.Text) Then
            txtBPSupineD.Text = txtBPD.Text
        End If
    End Sub

    Private Sub lkAssessment_ProcessNewValue(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles lkAssessment.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            lkAssessment.EditValue = Nothing
            lkAssessment.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblDiagnosis"
            .mintGrbId = 3
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            PopulateLookupDX(lkAssessment, "Diagnosis", "DiagnosisId", "LtblDiagnosis", "DiagnosisId,Diagnosis", , "Diagnosis", True)
            PopulateLookupDX(lkSeverity, "DiagnosisSeverity", "DiagnosisSeverityId", "LtblDiagnosisSeverity", "DiagnosisSeverityId,DiagnosisSeverity", , "DiagnosisSeverity", True)
            If mlngLookUpId > 0 Then
                lkAssessment.EditValue = CInt(mlngLookUpId)
            Else
                lkAssessment.EditValue = Nothing
                lkAssessment.Focus()
            End If

            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub btnPrintSick_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrintSick.Click
        Call SaveResult()
        If mstrFrmName <> "PatientInfo" Then
            Call ShowSickReport(VisitId, GetPatientId(VisitId), Me.ParentForm, mstrFrmName)
        Else
            Call ShowSickReport(VisitId, GetPatientId(VisitId), mdiMain, mstrFrmName)
        End If

    End Sub

    Private Sub lstlabTests_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstlabTests.DoubleClick
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblLabTests"
            .mintGrbId = 1
            .ShowInTaskbar = False
            .ShowDialog()
            'Populate LabTest checkList box
            PopulateList(lstlabTests, "SELECT LabTestId,LabTest  FROM LtblLabTests ORDER BY LabTest", "LabTest", "LabTestId")
            .Dispose()
            GC.Collect()
        End With
    End Sub


    Private Sub lstImages_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstImages.DoubleClick
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblImageType"
            .mintGrbId = 1
            .ShowInTaskbar = False
            .ShowDialog()
            'Populate Imaging checkList box
            PopulateList(lstImages, "SELECT ImageTypeId,ImageType  FROM LtblImageType ORDER BY ImageType", "ImageType", "ImageTypeId")
            .Dispose()
            GC.Collect()
        End With
    End Sub

    Private Sub lstSpecialists_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSpecialists.DoubleClick
        With frmSpecialist
            .ShowInTaskbar = False
            .mblnFrmOutside = True
            .ShowDialog()
            'Populate Specialist checkList box
            PopulateList(lstSpecialists, "SELECT DoctorId,(Firstname + ' ' + Lastname) as Name FROM tblSpecialists ORDER BY Name", "Name", "DoctorId")
            .Dispose()
            GC.Collect()
        End With

    End Sub

    Private Sub txtR_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtR.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtRespiratoryRate.Text = txtR.Text
        End If
    End Sub

    Private Sub txtRespiratoryRate_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtRespiratoryRate.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgRespiratory Then
            txtR.Text = txtRespiratoryRate.Text
        End If
    End Sub

    Private Sub txtT_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtT.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtTemperature.Text = txtT.Text
        End If
    End Sub

    Private Sub txtTemperature_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTemperature.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgGeneralAssessment Then
            txtT.Text = txtTemperature.Text
        End If
    End Sub

    Private Sub cmbTemperatureUnit_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbTemperatureUnit.EditValueChanged
        mblnChanged = True
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            lkTemperatureUnit.EditValue = CInt(cmbTemperatureUnit.EditValue)
        End If
    End Sub

    Private Sub lkTemperatureUnit_EditValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lkTemperatureUnit.EditValueChanged
        mblnChanged = True
        If xtcNotes.SelectedTabPage Is tpgGeneralAssessment Then
            cmbTemperatureUnit.EditValue = CInt(lkTemperatureUnit.EditValue)
        End If
    End Sub

    Private Sub txtP_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtP.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtPulse.Text = txtP.Text
        End If
    End Sub

    Private Sub txtPulse_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPulse.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgCardiology Then
            txtP.Text = txtPulse.Text
        End If
    End Sub

    Private Sub txtBPS_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBPS.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtBPSupineS.Text = txtBPS.Text
        End If
    End Sub

    Private Sub txtBPSupineS_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBPSupineS.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgCardiology Then
            txtBPS.Text = txtBPSupineS.Text
        End If
    End Sub

    Private Sub txtBPD_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBPD.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtBPSupineD.Text = txtBPD.Text
        End If
    End Sub

    Private Sub txtBPSittingD_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBPSittingD.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
       
    End Sub

    Private Sub btnSaveAsTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveAsTemplate.Click
        Dim strQuery As String = ""
        Dim blnIsTransactionOpen As Boolean
        Try
            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            If Template = "" And TemplateId = 0 Then

                Dim frmTempTemplate As New frmTemplate(0)
                With frmTempTemplate
                    .ShowDialog()
                    .Dispose()
                    GC.Collect()
                End With
                If Not IsDBNullOrNothing(Template) Then
                    strQuery = SmartReplace(Template)
                    If IsDBNullOrNothing(txtPC.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtPC.Text)
                    End If
                    If IsDBNullOrNothing(txtSummaryHistory.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtSummaryHistory.Text)
                    End If
                    If IsDBNullOrNothing(txtGen.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtGen.Text)
                    End If
                    If IsDBNullOrNothing(txtENT.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtENT.Text)
                    End If
                    If IsDBNullOrNothing(txtRS.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtRS.Text)
                    End If
                    If IsDBNullOrNothing(txtCVS.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtCVS.Text)
                    End If
                    If IsDBNullOrNothing(txtAbd.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtAbd.Text)
                    End If
                    If IsDBNullOrNothing(txtR.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtR.Text)
                    End If
                    If IsDBNullOrNothing(txtTemperature.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtTemperature.Text)
                    End If
                    If IsDBNullOrNothing(lkTemperatureUnit.EditValue) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & Val(lkTemperatureUnit.EditValue)
                    End If
                    If IsDBNullOrNothing(txtP.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtP.Text)
                    End If
                    If IsDBNullOrNothing(txtBPS.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtBPS.Text)
                    End If
                    If IsDBNullOrNothing(txtBPD.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtBPD.Text)
                    End If
                    If IsDBNullOrNothing(txtMu_SK.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtMu_SK.Text)
                    End If
                    If IsDBNullOrNothing(txtNS.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtNS.Text)
                    End If
                    If IsDBNullOrNothing(txtBloodSugar.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtBloodSugar.Text)
                    End If
                    If IsDBNullOrNothing(lkBloodSugar.EditValue) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(lkBloodSugar.EditValue)
                    End If
                    If IsDBNullOrNothing(txtUrine.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtUrine.Text)
                    End If
                    If IsDBNullOrNothing(lkAssessment.EditValue) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & Val(lkAssessment.EditValue)
                    End If
                    If IsDBNullOrNothing(lkSeverity.EditValue) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & Val(lkSeverity.EditValue)
                    End If
                    If IsDBNullOrNothing(txtInv.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtInv.Text)
                    End If
                    If IsDBNullOrNothing(txtTreatment.Text) Then
                        strQuery = strQuery & ",Null"
                    Else
                        strQuery = strQuery & "," & SmartReplace(txtTreatment.Text)
                    End If
                    Call InsertintoTable("tblTemplateDoctorNotes", strQuery)
                    MessageBox.Show("Template saved successfully", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    If TemplateId = 0 Then
                        TemplateId = GetId("tblTemplateDoctorNotes")
                    End If
                End If

            ElseIf TemplateId > 0 Then
                If IsDBNullOrNothing(txtPC.Text) Then
                    strQuery = "PC=Null"
                Else
                    strQuery = "PC=" & SmartReplace(txtPC.Text)
                End If
                If IsDBNullOrNothing(txtSummaryHistory.Text) Then
                    strQuery = strQuery & ",Subjective=Null"
                Else
                    strQuery = strQuery & ",Subjective=" & SmartReplace(txtSummaryHistory.Text)
                End If
                If IsDBNullOrNothing(txtGen.Text) Then
                    strQuery = strQuery & ",Gen=Null"
                Else
                    strQuery = strQuery & ",Gen=" & SmartReplace(txtGen.Text)
                End If
                If IsDBNullOrNothing(txtENT.Text) Then
                    strQuery = strQuery & ",ENT=Null"
                Else
                    strQuery = strQuery & ",ENT=" & SmartReplace(txtENT.Text)
                End If
                If IsDBNullOrNothing(txtRS.Text) Then
                    strQuery = strQuery & ",RS=Null"
                Else
                    strQuery = strQuery & ",RS=" & SmartReplace(txtRS.Text)
                End If
                If IsDBNullOrNothing(txtCVS.Text) Then
                    strQuery = strQuery & ",CVS=Null"
                Else
                    strQuery = strQuery & ",CVS=" & SmartReplace(txtCVS.Text)
                End If
                If IsDBNullOrNothing(txtAbd.Text) Then
                    strQuery = strQuery & ",ABD=Null"
                Else
                    strQuery = strQuery & ",ABD=" & SmartReplace(txtAbd.Text)
                End If
                If IsDBNullOrNothing(txtR.Text) Then
                    strQuery = strQuery & ",RPerMin=Null"
                Else
                    strQuery = strQuery & ",RPerMin=" & SmartReplace(txtR.Text)
                End If
                If IsDBNullOrNothing(txtTemperature.Text) Then
                    strQuery = strQuery & ",Temperature=Null"
                Else
                    strQuery = strQuery & ",Temperature=" & SmartReplace(txtTemperature.Text)
                End If
                If IsDBNullOrNothing(lkTemperatureUnit.EditValue) Then
                    strQuery = strQuery & ",TemperatureUnit=Null"
                Else
                    strQuery = strQuery & ",TemperatureUnit=" & Val(lkTemperatureUnit.EditValue)
                End If
                If IsDBNullOrNothing(txtP.Text) Then
                    strQuery = strQuery & ",PBeastPerMin=Null"
                Else
                    strQuery = strQuery & ",PBeastPerMin=" & SmartReplace(txtP.Text)
                End If
                If IsDBNullOrNothing(txtBPS.Text) Then
                    strQuery = strQuery & ",BP1=Null"
                Else
                    strQuery = strQuery & ",BP1=" & SmartReplace(txtBPS.Text)
                End If
                If IsDBNullOrNothing(txtBPD.Text) Then
                    strQuery = strQuery & ",BP2=Null"
                Else
                    strQuery = strQuery & ",BP2=" & SmartReplace(txtBPD.Text)
                End If
                If IsDBNullOrNothing(txtMu_SK.Text) Then
                    strQuery = strQuery & ",MuSk=Null"
                Else
                    strQuery = strQuery & ",MuSk=" & SmartReplace(txtMu_SK.Text)
                End If
                If IsDBNullOrNothing(txtNS.Text) Then
                    strQuery = strQuery & ",NS=Null"
                Else
                    strQuery = strQuery & ",NS=" & SmartReplace(txtNS.Text)
                End If
                If IsDBNullOrNothing(txtBloodSugar.Text) Then
                    strQuery = strQuery & ",BloodSugar=Null"
                Else
                    strQuery = strQuery & ",BloodSugar=" & SmartReplace(txtBloodSugar.Text)
                End If
                If IsDBNullOrNothing(lkBloodSugar.EditValue) Then
                    strQuery = strQuery & ",BloodSugarUnitID=Null"
                Else
                    strQuery = strQuery & ",BloodSugarUnitID=" & SmartReplace(lkBloodSugar.EditValue)
                End If
                If IsDBNullOrNothing(txtUrine.Text) Then
                    strQuery = strQuery & ",Urine=Null"
                Else
                    strQuery = strQuery & ",Urine=" & SmartReplace(txtUrine.Text)
                End If
                If IsDBNullOrNothing(lkAssessment.EditValue) Then
                    strQuery = strQuery & ",Assessment=Null"
                Else
                    strQuery = strQuery & ",Assessment=" & Val(lkAssessment.EditValue)
                End If
                If IsDBNullOrNothing(lkSeverity.EditValue) Then
                    strQuery = strQuery & ",Severity=Null"
                Else
                    strQuery = strQuery & ",Severity=" & Val(lkSeverity.EditValue)
                End If
                If IsDBNullOrNothing(txtInv.Text) Then
                    strQuery = strQuery & ",Inv=Null"
                Else
                    strQuery = strQuery & ",Inv=" & SmartReplace(txtInv.Text)
                End If
                If IsDBNullOrNothing(txtTreatment.Text) Then
                    strQuery = strQuery & ",Treatment=Null"
                Else
                    strQuery = strQuery & ",Treatment=" & SmartReplace(txtTreatment.Text)
                End If
                Call UpdateTable("tblTemplateDoctorNotes", strQuery, "TemplateId=" & TemplateId)
                MessageBox.Show("Template details updated successfully", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            End If
            If TemplateId > 0 Then
                Call DeleteFromTable("tblTemplateDoctorNotesDetails", "TemplateId=" & TemplateId)
                With lstReferrals
                    For intCtr As Integer = 0 To .ItemCount - 1
                        If .GetItemCheckState(intCtr) = CheckState.Checked Then
                            strQuery = TemplateId & "," & .GetItemValue(intCtr)
                            Call InsertintoTable("tblTemplateDoctorNotesDetails", strQuery)
                            bln = objDalHelper.InsertIntoTable("TRANS_FORMJ_DETAILS", strQuery)
                            If bln = False Then
                                If objDalHelper.BooleanTransaction = True Then objDalHelper.RollbackTransaction()
                                strInsertTransactionFormJ = "Cannot insert formJ"
                                Return strInsertTransactionFormJ
                            End If
                        End If
                    Next intCtr
                End With
            End If
            

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False


        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnLoadFromTemplate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadFromTemplate.Click
        Dim strQuery As String = ""
        Dim dsTemp As DataSet
        Try
            Dim frmTempTemplate As New frmTemplate(1)
            With frmTempTemplate
                .ShowDialog()
                .Dispose()
                GC.Collect()
            End With
            If TemplateId > 0 Then
                dsTemp = FillDataSet("Select * from tblTemplateDoctorNotes where TemplateId=" & TemplateId)
                With dsTemp.Tables(0)
                    If .Rows.Count > 0 Then
                        txtPC.Text = Trim(.Rows(0).Item("PC") & "")
                        txtSummaryHistory.Text = Trim(.Rows(0).Item("Subjective") & "")
                        txtGen.Text = Trim(.Rows(0).Item("Gen") & "")
                        txtENT.Text = Trim(.Rows(0).Item("ENT") & "")
                        txtRS.Text = Trim(.Rows(0).Item("RS") & "")
                        txtCVS.Text = Trim(.Rows(0).Item("CVS") & "")
                        txtAbd.Text = Trim(.Rows(0).Item("ABD") & "")
                        txtR.Text = Trim(.Rows(0).Item("RPerMin") & "")
                        txtT.Text = Trim(.Rows(0).Item("Temperature") & "")
                        If IsDBNullOrNothing(.Rows(0).Item("TemperatureUnit")) Then
                            lkTemperatureUnit.EditValue = Nothing
                        Else
                            lkTemperatureUnit.EditValue = .Rows(0).Item("TemperatureUnit")
                        End If
                        txtP.Text = Trim(.Rows(0).Item("PBeastPerMin") & "")
                        txtBPS.Text = Trim(.Rows(0).Item("BP1") & "")
                        txtBPD.Text = Trim(.Rows(0).Item("BP2") & "")
                        txtMu_SK.Text = Trim(.Rows(0).Item("MuSk") & "")
                        txtNS.Text = Trim(.Rows(0).Item("NS") & "")
                        txtBloodSugar.Text = Trim(.Rows(0).Item("BloodSugar") & "")
                        If IsDBNullOrNothing(.Rows(0).Item("BloodSugarUnitID")) Then
                            lkBloodSugar.EditValue = Nothing
                        Else
                            lkBloodSugar.EditValue = .Rows(0).Item("BloodSugarUnitID")
                        End If
                        txtUrine.Text = Trim(.Rows(0).Item("Urine") & "")
                        If IsDBNullOrNothing(.Rows(0).Item("Assessment")) Then
                            lkAssessment.EditValue = Nothing
                        Else
                            lkAssessment.EditValue = .Rows(0).Item("Assessment")
                        End If
                        If IsDBNullOrNothing(.Rows(0).Item("Severity")) Then
                            lkSeverity.EditValue = Nothing
                        Else
                            lkSeverity.EditValue = .Rows(0).Item("Severity")
                        End If
                        txtInv.Text = Trim(.Rows(0).Item("Inv") & "")
                        txtTreatment.Text = Trim(.Rows(0).Item("Treatment") & "")
                    End If
                End With
                dsTemp.Dispose()

                strQuery = "SELECT Referrals  as DoctorId FROM tblTemplateDoctorNotesDetails WHERE TemplateId=" & TemplateId
                dsTemp = FillDataSet(strQuery, "VisitReferrals")
                Dim i As Integer
                With dsTemp.Tables(0)
                    If .Rows.Count > 0 Then
                        'populate VisitReferrals checked list box
                        For i = 0 To .Rows.Count - 1
                            With lstReferrals
                                For intCtr As Integer = 0 To .ItemCount - 1
                                    If .GetItemValue(intCtr) = dsTemp.Tables("VisitReferrals").Rows(i).Item("DoctorId") Then
                                        .SetItemCheckState(intCtr, CheckState.Checked)
                                    End If
                                Next intCtr
                            End With
                        Next
                    End If
                End With
                dsTemp.Dispose()
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub rptxtDrugfrequency_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles rptxtDrugfrequency.ButtonClick
        If e.Button.Index = 1 Then
            Dim dsTemp2 As DataSet = FillDataSet("Select FrequencyId, Frequency from LtblFrequency")
            With rptxtDrugfrequency
                .Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.OK, "Refresh list")})
                .DataSource = dsTemp2.Tables(0)
                .DisplayMember = "Frequency"
                .ValueMember = "FrequencyId"
                .NullText = ""
                .View.Columns("FrequencyId").Visible = False
                .View.Columns("FrequencyId").Visible = False
            End With

        End If
    End Sub

    Private Sub cboHospital_ButtonClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles cboHospital.ButtonClick
        If e.Button.Index = 1 Then
            Call PopulateLookupDX(cboHospital, "Hospital Name", "HospitalId", "LtblHospital", "HospitalId,HospitalName [Hospital Name]", , "HospitalName", , , 250)
        End If
    End Sub

    Private Sub cboHospital_ProcessNewValue(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs) Handles cboHospital.ProcessNewValue
        If IsDBNullOrNothing(e.DisplayValue) = True Then Exit Sub
        If MessageBox.Show("This value is not present in the list. Do you want to add it now?", gstrMessage, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            cboHospital.EditValue = Nothing
            cboHospital.Focus()
            Exit Sub
        End If
        With frmToolsLookUp
            .mblnFrmOtherForm = True
            .mstrLookUpValue = "LtblHospital"
            .mintGrbId = 1
            .mstrItemName = e.DisplayValue
            .ShowDialog()
            Call PopulateLookupDX(cboHospital, "Hospital Name", "HospitalId", "LtblHospital", "HospitalId,HospitalName [Hospital Name]", , "HospitalName", , , 250)
            If mlngLookUpId > 0 Then
                cboHospital.EditValue = CInt(mlngLookUpId)
            Else
                cboHospital.EditValue = Nothing
                cboHospital.Focus()
            End If
            .Dispose()
            GC.Collect()
        End With
        mlngLookUpId = Nothing
    End Sub

    Private Sub txtTreatment_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTreatment.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgSummary Then
            txtTherapy.Text = txtTreatment.Text
        End If
    End Sub

    Private Sub txtTherapy_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtTherapy.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgManagement Then
            txtTreatment.Text = txtTherapy.Text
        End If
    End Sub

    Private Sub lstReferrals_ItemCheck(ByVal sender As System.Object, ByVal e As DevExpress.XtraEditors.Controls.ItemCheckEventArgs) Handles lstReferrals.ItemCheck
        If sender.text <> "" Then
            mblnChanged = True
        End If
        'Dim i As Integer 'loop variable
        'For i = 0 To lstReferrals.ItemCount - 1
        '    If lstReferrals.GetItemChecked(i) = True Then
        '        lstSpecialists.Items(i).CheckState = CheckState.Checked
        '    Else
        '        lstSpecialists.Items(i).CheckState = CheckState.Unchecked
        '    End If
        'Next
    End Sub

    Private Sub txtRS_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtRS.TextChanged, txtCVS.TextChanged, txtInv.TextChanged, txtUrine.TextChanged, txtNS.TextChanged, txtMu_SK.TextChanged, txtBloodSugar.TextChanged, txtWeight.TextChanged, txtHeight.TextChanged, txtHeadCircimference.TextChanged, txtAbdominalGirth.TextChanged, txtNodes.TextChanged, txtHandsArms.TextChanged, txtSkin.TextChanged, txtBreastCondition.TextChanged, txtVolume.TextChanged, txtRhythm.TextChanged, txtBPStandingS.TextChanged, txtBPSittingS.TextChanged, txtVenous.TextChanged, txtThrill.TextChanged, txtS2.TextChanged, txtS1.TextChanged, txtMurmurs.TextChanged, txtJVPWave.TextChanged, txtJVPHeight.TextChanged, txtHeartInspection.TextChanged, txtBPStandingD.TextChanged, txtArterial.TextChanged, txtApexPosition.TextChanged, txtApexCharacter.TextChanged, txtAddedSound.TextChanged, txtSputum.TextChanged, txtRepiratoryEffort.TextChanged, txtTrachea.TextChanged, txtTonsils.TextChanged, txtSinuses.TextChanged, txtPharnyx.TextChanged, txtNose.TextChanged, txtEar.TextChanged, txtChestPercussion.TextChanged, txtChestPalpitation.TextChanged, txtChestInspection.TextChanged, txtChestAuscultation.TextChanged, txtThoughtProcess.TextChanged, txtSpeech.TextChanged, txtRectum.TextChanged, txtOrientation.TextChanged, txtObsessions.TextChanged, txtMood.TextChanged, txtMemory.TextChanged, txtIntelligence.TextChanged, txtInsightJudgement.TextChanged, txtHallucinations.TextChanged, txtGenitaliaPalpitation.TextChanged, txtGenitaliaInspection.TextChanged, txtGeneralInformation.TextChanged, txtGeneralAppearance.TextChanged, txtDelusion.TextChanged, txtAttentionConcentration.TextChanged, txtAnus.TextChanged, txtAbodmenInspection.TextChanged, txtAbdomenPercussion.TextChanged, txtAbdomenPalpitation.TextChanged, txtAbdomenAuscultation.TextChanged, txtSensoryVibration.TextChanged, txtSensoryTouch.TextChanged, txtSensoryTemperature.TextChanged, txtSensoryPosition.TextChanged, txtGcsTotalScore.TextChanged, txtCranialNerveXII.TextChanged, txtCranialNerveXI.TextChanged, txtCranialNerveX.TextChanged, txtCranialNerveVIII.TextChanged, txtCranialNerveVII.TextChanged, txtCranialNerveIX.TextChanged, txtCranialNerveIII.TextChanged, txtCranialNerveII.TextChanged, txtCranialNerveI.TextChanged, txtCerebellumTandemWalking.TextChanged, txtCerebellumRapidlyRepeated.TextChanged, txtCerebellumHeelToChin.TextChanged, txtCerebellumFingerToNose.TextChanged, txtSpine.TextChanged, txtSickDays.TextChanged, txtOther.TextChanged, txtMuscles.TextChanged, txtJoints.TextChanged, txtGait.TextChanged, txtBones.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
    End Sub

    Private Sub lkAssessment_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkAssessment.EditValueChanged, lkSeverity.EditValueChanged, lkBloodSugar.EnabledChanged, cmbWeightUnit.EditValueChanged, cmbHeightUnit.EditValueChanged, cmbHeadCircumferenceUnit.EditValueChanged, cmbAbdominalGirthUnit.EditValueChanged, cmbOedema.EditValueChanged, cmbNutrition.EditValueChanged, cmbMucus4.EditValueChanged, cmbMucus3.EditValueChanged, cmbMucus2.EditValueChanged, cmbMucus1.EditValueChanged, cmbHydration.EditValueChanged, cmbReflexRightT.EditValueChanged, cmbReflexRightP.EditValueChanged, cmbReflexRightK.EditValueChanged, cmbReflexRightB.EditValueChanged, cmbReflexRightABDup.EditValueChanged, cmbReflexRightABDlow.EditValueChanged, cmbReflexRightA.EditValueChanged, cmbReflexLeftT.EditValueChanged, cmbReflexLeftP.EditValueChanged, cmbReflexLeftK.EditValueChanged, cmbReflexLeftB.EditValueChanged, cmbReflexLeftABDup.EditValueChanged, cmbReflexLeftABDlow.EditValueChanged, cmbReflexLeftA.EditValueChanged, cmbGcsEyeOpening.EditValueChanged, cmbGcsBestVerablResponse.EditValueChanged, cmbGcsBestMotorResponse.EditValueChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
    End Sub

    Private Sub txtBPSupineD_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBPSupineD.TextChanged
        If sender.text <> "" Then
            mblnChanged = True
        End If
        If xtcNotes.SelectedTabPage Is tpgCardiology Then
            txtBPD.Text = txtBPSupineD.Text
        End If
    End Sub

    Private Sub dtSickStartDate_EditValueChanged_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtSickStartDate.EditValueChanged
        mblnChanged = True
        If Not IsDBNullOrNothing(dtSickStartDate.EditValue) AndAlso Not IsDBNullOrNothing(dtSickEndDate.EditValue) Then
            If CDate(dtSickStartDate.EditValue) > CDate(dtSickEndDate.EditValue) Then
                MessageBox.Show("Please select proper end date", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                dtSickEndDate.EditValue = Nothing
                txtSickDays.Text = Nothing
                dtSickEndDate.Focus()
                Exit Sub
            End If
            txtSickDays.Text = DateDiff(DateInterval.Day, CDate(dtSickStartDate.EditValue), DateAdd(DateInterval.Day, 1, CDate(dtSickEndDate.EditValue)))
        Else
            txtSickDays.Text = Nothing
        End If
    End Sub

    Private Sub dtSickEndDate_EditValueChanged1(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtSickEndDate.EditValueChanged
        mblnChanged = True
        If Not IsDBNullOrNothing(dtSickStartDate.EditValue) AndAlso Not IsDBNullOrNothing(dtSickEndDate.EditValue) Then
            If CDate(dtSickStartDate.EditValue) > CDate(dtSickEndDate.EditValue) Then
                MessageBox.Show("Please select proper end date", gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                dtSickEndDate.Focus()
                dtSickEndDate.EditValue = Nothing
                txtSickDays.Text = Nothing
                Exit Sub
            End If
            txtSickDays.Text = DateDiff(DateInterval.Day, CDate(dtSickStartDate.EditValue), DateAdd(DateInterval.Day, 1, CDate(dtSickEndDate.EditValue)))
        Else
            txtSickDays.Text = Nothing
        End If
    End Sub
End Class
